Next.js:如何更改特定页面上根 div __next 的 css?

Ruk*_*ith 13 jsx reactjs next.js

我想更改__next登录页面上id 的 div 。但是当我在 jsx 中添加样式时,当 dom 挂载到页面时,它似乎更改为另一个 ID 为#__next.jsx-2357705899, .main.jsx-2357705899 的div 。

__next挂载登录页面时如何更改div 的css ?

<style jsx>{`
  #__next,
  .main {
    height: 100%;
  }
`}</style>
Run Code Online (Sandbox Code Playgroud)

小智 42

也许这对某人有帮助。
创建一个文件夹“styles”添加“globals.css”

将其添加到该文件中

@tailwind components;
@tailwind utilities;
@layer components {
    #__next {
        @apply h-full bg-red-500;
    }
    html,
    body {
        @apply h-full;
    }
}
Run Code Online (Sandbox Code Playgroud)
转到您的 _app.js 并导入上面的样式表。


Sky*_*Key 20

Next.JS 的 Styled JSX 允许您向元素添加global关键字<style>。这是自定义__nextdiv 的方式。

在你pages/_document.js这样做:

// pages/_document.js
import Document, { Head, Main, NextScript } from "next/document";

export default class MyDocument extends Document {
  render() {
    return (
      <html>
        <Head />
        <body>
          <Main />
          <NextScript />
          <style jsx global>{`
            /* Other global styles such as 'html, body' etc... */

            #__next {
              height: 100%;
            }
          `}</style>
        </body>
      </html>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 现在`_document.js`中的`全局样式`不生效。现在必须在“_app.js”中应用样式。 (3认同)

iur*_*rii 3

您可以执行的解决方法之一是#__next在登录页面上手动添加一个类,然后对其进行全局样式设置

import React from 'react';

export default class LoginPage extends React.Component {
  componentDidMount() {
    document.getElementById('__next').classList.add('login-page');
  }

  componentWillUnmount() {
    document.getElementById('__next').classList.remove('login-page');
  }

  render() {
    return (
      <div>
        Login page
        <style jsx global>{`
          .login-page {
            background-color: red;
          }
        `}</style>
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)