为什么我的元素没有使用相同的反应状态实例?

问题描述

我正在做一个随机报价应用程序,当我尝试更改正文背景文本框文本颜色时,我似乎使用了错误的反应状态。车身背景颜色始终落后一步,我希望它们同时变为相同的颜色。 知道我的代码有什么问题吗?我只是在这里添加了开展业务的类组件。

P.S。我希望我的代码不太难读,我是一个初学者

class Quote extends React.Component {
  constructor() {
    super();
    this.state = {
      quote: [],author: [],apiData:[],color: ""
    };
    this.handleClick = this.handleClick.bind(this)
  }

  componentDidMount() {
    //Here I made an API call for this.state.apiData to get my quotes
  }
  
  handleClick(){

    var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16);        //Here I get a random color


    function getRandNum(min,max){
      return Math.floor(Math.random()*(max-min)+min)          //Here I get a random number in the range of my API array length
    }
    let randomNum = getRandNum(0,this.state.apiData.length)


    this.setState({
      quote: this.state.apiData[randomNum].text,author: this.state.apiData[randomNum].author
      color: randomColor
    }) 
    
    document.body.style.backgroundColor = this.state.color;
 
    console.log(this.state.color)
  }
  
  render() {
    return (
      <div class="quote-box">

        <h1 style={{color: this.state.color}}> {this.state.quote}-"{this.state.author}" </h1>

        <button 
                onClick={this.handleClick} 
                class="change-button" 
                style={{color: "white",backgroundColor: this.state.color}}
        >Change
        </button>

      </div>
    );
  }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)