next.js 有没有更好的方法将类放入下一个.js中的html和body标签中?

7fyelxc5  于 2023-06-05  发布在  其他
关注(0)|答案(2)|浏览(124)

我正在使用Next.js和Tailwind,为了让一些元素正确显示,我需要将一些样式类放入<html><body>中。
我对我的MyApp做了这个

function MyApp({ Component, pageProps}: AppProps) {
  useEffect(() => {
    document.querySelector("html").classList.add("h-full");
    document.querySelector("body").classList.add("h-full");
    document.querySelector("#__next").classList.add("h-full");
  });

  return (
      <Component {...pageProps} />
  )
}

这是工作...但我想知道是否有其他的方法,或更优雅的解决方案。

6qftjkof

6qftjkof1#

我们使用这两种方法,并使用以下内容创建了一个_document.tsx文件:

import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
    return (
        <Html lang="en-us" className="h-full">
            <Head />
            <body className="h-full">
                <Main />
                <NextScript />
            </body>
        </Html>
    )
}

我们在一些Tailwind CSS/Next.js研究中发现了这一点,它对我们很有效。

gupuwyp2

gupuwyp22#

我正在使用下一个js,功能组件,这对我很有效

useEffect(() => {
if (modalOpen) {
  document.querySelector("html")?.classList.add("!overflow-y-hidden");
} else {
  document.querySelector("html")?.classList.remove("!overflow-y-hidden");
}

},[modalOpen]);

相关问题