【问题标题】:Changing background color depending on state in react.js根据 react.js 中的状态更改背景颜色
【发布时间】:2020-11-03 16:16:01
【问题描述】:

我正在开发一个简单的应用程序,背景颜色应根据季节而有所不同。到目前为止,我已经写了:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
        backgroundColor: 'blue'
    }
  }

    handleSeason = (time) => {
    const months = [
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
      'July',
      'August',
      'September',
      'October',
      'November',
      'December',
    ]
    const month = months[time.getMonth()];

    if (month === 'January' || month === 'February' || month === 'December') {
      this.setState({backgroundColor: 'white'});
    } else if
      (month === 'March' || "April" || 'May') {
      this.setState({ backgroundColor: 'yellow' });
    } else if 
    (month==='June' || month ==='July' ||month ==='August'){
      this.setState({ backgroundColor: 'green' });
     } else {
      this.setState({ backgroundColor: 'red' });
    }
  }

  

在渲染中,我返回以下 div:

      <div className='app' style={{backgroundColor: this.state.backgroundColor }}>

背景保持蓝色。我不确定问题出在哪里。控制台显示没有错误。任何提示将不胜感激。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    我没有看到任何会触发 handleSeason 功能的东西...

    也许尝试一下会很好:

    componentDidMount() {
      this.handleSeason(new Date())
    }
    

    【讨论】:

      【解决方案2】:

      你有两件事要在代码中修复

      第二个if块是这样的

      (month === 'March' || "April" || 'May') {
      

      这将始终将状态设置为黄色,因为字符串 April 和 May 将被视为 true,因此如下所示进行更改

         else if (month === "March" ||month ===  "April" ||month ===  "May") {
      

      同时检查你是否调用了handleSeason函数,如下所示

      this.handleSeason(new Date());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-03
        • 1970-01-01
        • 2015-09-26
        • 2018-10-01
        • 1970-01-01
        • 2019-11-20
        • 2016-10-16
        相关资源
        最近更新 更多