你可以修改 NextJS 挂载元素或向 __next div 添加类吗?

Dil*_*ing 6 javascript css jsx next.js tailwind-css

长话短说,我正在做一个项目,我想让内容“填充”静态标题下方的垂直空间。我在 React 中使用顺风完成了这样的操作:

<body class="flex flex-col h-screen text-gray-600 work-sans leading-normal text-base tracking-normal">
    <header class="flex h-18 bg-white shadow-md">
        {/* header menu options */}
    </header>
    <div class="flex flex-1 h-full bg-gray-200 p-6">
        {/* page content */}
    </div>
Run Code Online (Sandbox Code Playgroud)

但是对于 NextJS,它似乎将安装 div(即<div id="__next">)放在正文和内容的 wrest 之间。如果我修改 CSS 以提供#__next { height: %100 }但使填充无法正常工作,它会溢出。所以它看起来像这样:

<body class="flex flex-col h-screen text-gray-600 work-sans leading-normal text-base tracking-normal">
    <div id="__next">
        <header class="flex h-18 bg-white shadow-md">
            {/* header menu options */}
        </header>
        <div class="flex flex-1 h-full bg-gray-200 p-6">
            {/* page content */}
        </div>
    </div>
Run Code Online (Sandbox Code Playgroud)

以下是屏幕截图,可以直观地看到额外 div 导致问题的原因:https : //imgur.com/a/dHRsDkY

解决这个理论上可行的问题的两个可能选项是向#__nextdiv添加类或挂载到正文而不是#__nextdiv。有谁知道如何实现其中任何一个?

编辑:是的,我想我可以将布局更改为固定的标题和内容元素顶部的填充,这会回避问题,这可能最终成为我需要的解决方法,但我仍然有兴趣知道是否我提到的解决方案中的一部分是可能的,因为如果不是,那是 NextJS 的技术限制,不会引起太多关注。

Abb*_*bas 12

我通过从主体中删除类并将它们应用到#__next容器 div 来解决这个问题:

我在本示例中使用了将 tailwind 与 Next.js 结合使用的方法。

然后我编辑了styles/index.css

@tailwind base;

/* Write your own custom base styles here */
/* #__next {
  height: 100%;
} */

/* Start purging... */
@tailwind components;
/* Stop purging. */

html,
body {
  @apply bg-gray-50 dark:bg-gray-900;
}

#__next {
  @apply flex flex-col h-screen text-gray-600 leading-normal text-base tracking-normal;
}

/* Write your own custom component styles here */
.btn-blue {
  @apply px-4 py-2 font-bold text-white bg-blue-500 rounded;
}

/* Start purging... */
@tailwind utilities;
/* Stop purging. */

/* Your own custom utilities */

Run Code Online (Sandbox Code Playgroud)

正如您所说,重点是将类添加到#__next而不是body.

正如您在评论中看到的,在哪里添加指令很重要@apply

重要的几行是:

#__next {
  @apply flex flex-col h-screen text-gray-600 leading-normal text-base tracking-normal;
}
Run Code Online (Sandbox Code Playgroud)

正如您在问题标题中所问的,这是向容器 div 添加顺风样式的一种方法#__next

另一种解决方案是在组件或页面加载后使用componentDidMount()生命周期钩子或useEffect如下钩子设置类:

useEffect(() => {
    document.querySelector("#__next").className =
      "flex flex-col h-screen text-gray-600 leading-normal text-base tracking-normal";
  }, []);
Run Code Online (Sandbox Code Playgroud)

如果您查看有关自定义文档的 Next.js 文档,您可以看到组件MainNextScript是 Next.js 的内部结构,并且是页面正确呈现所必需的,并且您无法更改 Next.js 内部结构,因此我认为上面提到的解决方案是将类添加到 #__next 容器 div 的最佳方法。