簡體   English   中英

如何通過單擊按鈕在 Reactjs 中使用 state 更改每個單獨 div 的背景顏色?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM