我在这里使用这个例子
https://github.com/zeit/next.js#custom-document
我想改变习惯_在body标记上使用
我尝试过在调用组件时传递道具,但都不起作用。我想添加一个基于某些条件的“暗”类,但我不知道如何改变这一点。
编辑:
我不确定这是否可能。在从nextjs slack频道得到帮助后,我被告知
"Pages get rendered client side with next/link
And body is not touched after server side rendering"
我将尝试将内容包装在我生成的另一个标记中,并尝试更改这一点。
发布于 2019-02-20 04:28:27
我发现的最干净的解决方案不是声明性的,但它工作得很好:
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属性。
发布于 2021-01-06 02:24:20
在当前的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") } );
请注意,useEffect是一个钩子,所以它只能在现代功能组件中使用,而不能在类组件中使用。
可以使用useEffect钩子来代替“旧的”componentDidMount LifeCycle。
https://reactjs.org/docs/hooks-effect.html
发布于 2020-12-12 02:55:47
对于不需要很多唯一主体类的情况,我想出的解决方案是创建一个名为BodyClass.js的组件,并将该组件导入到我的Layout.js组件中。
BodyClass.js
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
import Header from './Header';
import Footer from './Footer';
import BodyClass from '../BodyClass';
const Layout = ({ children }) => {
return (
{children}
)
}
export default Layout;
https://stackoverflow.com/questions/49609211
复制相似问题