![](/img/trans.png)
[英]Given a handsontable with multiple columns each using a different renderer, how can I change individual cell background-color upon data update?
[英]How can i change the background color of each individual div using state in Reactjs by clicking a button?
我想通過單擊一個按鈕來更改每個 div 的背景顏色。 我希望它的工作方式是:
他們都是從白色開始的。 然后單擊按鈕,頂部 div 變為藍色。 再次單擊第一個 div 變為白色,第二個 div 變為藍色。 再次單擊,第三個變為藍色,第二個變為白色。 再次單擊,第三個變為白色,第一個變為藍色,並且繼續運行。
import React, { Component } from 'react';
class Page extends Component {
constructor(props) {
super(props);
this.state = {
color:"white"
}
}
changeColor = () => {
if(this.state.color ==="white"){
this.setState({color:"blue"})
}
if (this.state.color === "blue") {
this.setState({ color: "white" })
}
}
render() {
return (
<>
<div className="box" style={{background:this.state.color}}></div>
<div className="box" style={{ background: this.state.color}}></div>
<div className="box" style={{ background: this.state.color }}></div>
<button onClick={this.changeColor}>Click me</button>
</>
);
}
}
export default Page;
您可以在 state 中使用計數而不是顏色,這樣您就知道要在哪個 div 上設置背景:
class Page extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
}
}
changeColor = () => {
let next = this.state.count + 1;
if (next === 4) {
next = 0;
}
this.setState({count: next})
}
render() {
return (
<>
<div className="box" style={{ background: this.state.count === 1 ? "blue" : "white" }}>a</div>
<div className="box" style={{ background: this.state.count === 2 ? "blue" : "white" }}>b</div>
<div className="box" style={{ background: this.state.count === 3 ? "blue" : "white" }}>c</div>
<button onClick={this.changeColor}>Click me</button>
</>
);
}
}
每個 div 負責設置自己的背景。 我還將 a、b 和 c 放在 div 中,因為它們沒有任何內容就不會顯示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.