Next.js 使用 _document.js 在身体上自定义类

324*_*423 11 javascript reactjs next.js

我在这里使用这个例子

https://github.com/zeit/next.js#custom-document
Run Code Online (Sandbox Code Playgroud)

我想更改 body 标签上的 custom_class

我试过在调用组件时传递道具,但没有任何效果。我想根据某些条件添加一个“暗”类,但我不知道如何更改。

编辑:

我不确定这是可能的。从 nextjs slack 频道获得帮助后,我被告知

"Pages get rendered client side with next/link
And body is not touched after server side rendering"
Run Code Online (Sandbox Code Playgroud)

我将尝试将内容包装在我生成的另一个标签中并尝试更改它。

Jac*_*uen 11

我找到的最干净的解决方案不是声明性的,但效果很好:

import Head from "next/head"

class HeadElement extends React.Component {
    componentDidMount() {
        const {bodyClass} = this.props
        document.querySelector("body").classList.add(bodyClass || "light")
    }

    render() {
        return <Head>
            {/* Whatever other stuff you're using in Head */}
        </Head>
    }
}

export default HeadElement
Run Code Online (Sandbox Code Playgroud)

使用此 Head 组件,您将传入“dark”或“light”(遵循浅色/深色主题的问题示例)作为页面中的 bodyClass 道具。


Luc*_*lin 5

从当前的 Next (10) 和 React (17) 版本开始,如果您想从页面更改 body 类,可以这样做:

// only example: maybe you'll want some logic before, 
// and maybe pass a variable to classList.add()
useEffect( () => { document.querySelector("body").classList.add("home") } );
Run Code Online (Sandbox Code Playgroud)

请注意 useEffect 是一个 Hook,因此它只能在现代函数组件中使用,而不能在类组件中使用。

可以使用 useEffect Hook 代替“旧”componentDidMount LifeCycle。

https://reactjs.org/docs/hooks-effect.html https://reactjs.org/docs/hooks-overview.html https://reactjs.org/docs/components-and-props.html

  • 你需要在 useEffect 依赖项末尾添加 [] 来仅调用它一次,否则它将在每个页面重新渲染时调用 (2认同)

Jos*_*can 0

这并不完全是您正在寻找的答案,但我能够通过组件传递一个 prop 来完成同样的事情,然后更新一个顶级元素上的类,该元素包装了我的应用程序中的所有内容,并且位于 . 这样,每个页面都可以拥有自己独特的类,并且以与我使用主体类相同的方式进行操作。

这是我传递道具的地方

<Layout page_title={meta_title} page_desc={meta_desc} main_class={'contact_page'}>
Run Code Online (Sandbox Code Playgroud)

这是我在布局组件中使用它的地方:

<main className={props.main_class}>
    <Header page_title={props.page_title} page_desc={props.page_desc} />

      {props.children}

    <Footer />
</main>
Run Code Online (Sandbox Code Playgroud)