gpt4 book ai didi

reactjs - 更改 元素上的样式

转载 作者:行者123 更新时间:2023-12-03 14:00:18 25 4
gpt4 key购买 nike

我是 React 新手,所以这可能很简单,但我一生都无法在文档中找到任何内容,因为该元素位于 ReactDOM 之外。

我使用material-ui作为用户界面,它提供了两个主题:lightBaseTheme (默认值)和 darkBaseTheme颜色较深。某种白天和夜间模式。问题是没有对 <body> 应用任何样式。所以页面背景不符合主题。深色主题使用白色文本,在默认白色背景上不会显示。

我怀疑我需要找到一个编程解决方案并根据当前加载的主题设置背景颜色。

但是怎么办呢?我尝试将代码放入顶级组件的 componentDidUpdate 方法中,但这似乎总是返回浅色主题。无论如何,我不确定直接写入 DOM 是否是一个好习惯,即使 body元素位于任何将受 React 影响的元素之外。

export default class app extends React.Component {

componentDidUpdate () {
const muiTheme = getMuiTheme();
const canvasColor = muiTheme.palette.canvasColor;
document.body.style.backgroundColor = canvasColor;
}

render () {
const muiTheme = getMuiTheme();
return (
<MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}>
<span>Rest of the app goes here</span>
</MuiThemeProvider>
);
}
};

即使在渲染调用中设置了 lightBaseTheme,在 componentDidUpdate 中对 getMuiTheme 的调用也始终返回 lightBaseTheme。

我或许应该补充一点,最终的目的是能够动态更改主题,从而直接对 <body 进行样式设置。元素不是一个选项。

最佳答案

如果可能,最好的解决方案是除了 style props 之外,在 React 应用程序中使用顶级 div 来解决您的问题。

但是,您现在所拥有的将不起作用,因为 componentDidUpdate() 在初始化时不会被调用,并且加载后您似乎没有使用 props/state 对其进行任何更新.

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render. (React Docs)

相反,请使用 componentDidMount(),它会在组件安装到 DOM 后立即调用。

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering. (React Docs)

Here's a good write up on the component lifecycle .

关于reactjs - 更改 <body> 元素上的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40746413/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com