我正在尝试通过单击按钮将 html 正文的背景颜色更改为红色, 但我只知道如何使用已经在 body 内部的元素,而不是 body 本身。
class App extends Component {
constructor(props) {
super(props);
this.state = {
bgColor: ""
};
}
boxClick = e => {
this.setState({
bgColor: "red"
});
};
render() {
return (
<div className="App">
<article className="experimentsHolder">
<div
className="boxClickCss"
style={{ backgroundColor: this.state.bgColor }}
onClick={this.boxClick}
>
Click Me!
</div>
</article>
</div>
);
}
}
如您所见,我将 style={{backgroundColor: this.state.bgColor}}
添加到 div,但我无法将其添加到 body 中,因为它不在该文件中。有帮助吗?
最佳答案
在生命周期方法
中操作DOM 通常是一个好习惯See doc here .如果这对您很重要,您可以在 App.js 组件上使用 componentDidUpdate
生命周期方法,并从那里使用标准 dom 操作来查找正文并更新其背景颜色。您还可以检查该方法以确保在对其执行操作之前先前状态和当前状态已更改。它可能看起来像这样:
class App extends Component {
constructor(props) {
super(props);
this.state = {
bgColor: ""
}
}
componentDidUpdate(prevProps, prevState){
const { bgcolor } = this.state;
if(prevProps.bgColor !== bgColor){
const bodyElt = document.querySelector("body");
bodyElt.style.backgroundColor = bgcolor;
}
}
关于javascript - 使用 React 在单击时更改正文元素的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55051009/