首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用_document.js的body上的Next.js自定义类

使用_document.js的body上的Next.js自定义类
EN

Stack Overflow用户
提问于 2018-04-02 18:03:58
回答 5查看 19.3K关注 0票数 15

我在这里使用这个例子

代码语言:javascript
复制
https://github.com/zeit/next.js#custom-document

我想改变习惯_在body标记上使用

我尝试过在调用组件时传递道具,但都不起作用。我想添加一个基于某些条件的“暗”类,但我不知道如何改变这一点。

编辑:

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

代码语言:javascript
复制
"Pages get rendered client side with next/link
And body is not touched after server side rendering"

我将尝试将内容包装在我生成的另一个标记中,并尝试更改这一点。

EN

回答 5

Stack Overflow用户

发布于 2019-02-20 04:28:27

我发现的最干净的解决方案不是声明性的,但它工作得很好:

代码语言:javascript
复制
import Head from "next/head"

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

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

export default HeadElement

使用这个Head组件,您将传入"dark“或"light”(按照问题的亮/暗主题示例)作为页面的bodyClass属性。

票数 14
EN

Stack Overflow用户

发布于 2021-01-06 02:24:20

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

代码语言:javascript
复制
// only example: maybe you'll want some logic before, 
// and maybe pass a variable to classList.add()
useEffect( () => { document.querySelector("body").classList.add("home") } );

请注意,useEffect是一个钩子,所以它只能在现代功能组件中使用,而不能在类组件中使用。

可以使用useEffect钩子来代替“旧的”componentDidMount LifeCycle。

https://reactjs.org/docs/hooks-effect.html

https://reactjs.org/docs/hooks-overview.html

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

票数 9
EN

Stack Overflow用户

发布于 2020-12-12 02:55:47

对于不需要很多唯一主体类的情况,我想出的解决方案是创建一个名为BodyClass.js的组件,并将该组件导入到我的Layout.js组件中。

BodyClass.js

代码语言:javascript
复制
import  { Component } from 'react';

class BodyClass extends Component {

    componentDidMount() {

        if (window.location.pathname == '/') {
            this.setBodyClass('home');
            
        } else if (window.location.pathname == '/locations') {
            this.setBodyClass('locations');
        } 
    }

    setBodyClass(className) {
        // remove other classes
        document.body.className ='';

        // assign new class
        document.body.classList.add(className);
    }

    render() { 
        return null;
    }

}
 
export default BodyClass;

Layout.js

代码语言:javascript
复制
import Header from './Header';
import Footer from './Footer';
import BodyClass from '../BodyClass';

const Layout = ({ children }) => {

    return (

        

            

            

            {children}
            
            

        

    )

}


export default Layout;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49609211

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档