我试图通过单击一个按钮来随机更改整个页面的背景颜色,但是它只是在更改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按钮时,我需要更改整个页面的背景色。您的帮助将不胜感激
答案 0 :(得分:3)
body标签不受React的控制。要修改componentDidMount
生命周期上的body标签挂钩,并使用香草javascript
这是https://jaketrent.com/post/update-body-class-react/
的一种方式在坚果壳中添加以下逻辑
componentDidMount() {
document.body.style.backgroundColor = this.state.colors;
}
答案 1 :(得分:1)
Ramesh给出了正确的答案,这是演示:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
colors: ["red", "yellow", "blue", "green", "purple", "pink"]
};
}
changeBg() {
const { colors } = this.state;
const color = colors[Math.floor(Math.random() * colors.length)];
document.body.style.backgroundColor = color;
}
render() {
return (
<div>
<button onClick={() => this.changeBg()}>Change Color</button>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
答案 2 :(得分:0)
import React from "react";
function MyComponent({ name }) {
// I found this formula
// here: https://css-tricks.com/snippets/javascript/random-hex-color/
let randomColor = Math.floor(Math.random() * 16777215).toString(16);
// The trouble I had was about how to use
// the variable randomColor in "style:{}" tag
return (
<div className="parent-container">
<div
className="child-container"
style={{ backgroundColor: "#" + `${randomColor}` }}
>
<h4 className="name">{name}</h4>
</div>
</div>
);
}
export default MyComponent;