gpt4 book ai didi

javascript - 通过单击随机更改 react 应用程序的背景颜色

转载 作者:行者123 更新时间:2023-11-29 17:39:36 24 4
gpt4 key购买 nike

我试图通过单击按钮随机更改整个页面的背景颜色,但它只是更改了 div 元素的背景。这是我的代码

  import React from "react";
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
quotes: ["red", "yellow", "blue", "green", "purple", "pink"],
colors: [],
};
this.nextColor = this.nextColor.bind(this);
}
// moves to display next quotes
nextColor() {
const random = this.state.quotes[Math.floor(Math.random() * this.state.quotes.length)]
console.log("receiving ", random);
this.setState({
colors: random
})
}
render() {
return (
<div style={{backgroundColor: this.state.colors}}>
<h1>{this.state.colors}</h1>
<button onClick={this.nextColor}>Next Color</button>
</div>
)
}
}

ReactDOM.render(<Home />, document.getElementById("app"));

我需要在单击 nextColor 按钮时更改整个页面的背景颜色。您的帮助将不胜感激

最佳答案

body 标签不受 React 控制。修改 body 标签 Hook 到 componentDidMount 生命周期并使用 vanilla javascript 设置颜色

这里有一个方法 https://jaketrent.com/post/update-body-class-react/

简而言之,添加以下逻辑

  componentDidMount() {
document.body.style.backgroundColor = this.state.colors;
}

关于javascript - 通过单击随机更改 react 应用程序的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53878153/

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