【问题标题】:React - change button color after clickingReact - 单击后更改按钮颜色
【发布时间】:2018-08-01 02:41:41
【问题描述】:

我有以下按钮:

{this.steps.map((step, index) => (
    <Button variant="raised" color={(step.answer === 'done' ? 'primary' : 'default')}
                            onClick={this.markAs('done', step)}>
                                Done
                            </Button>
)}

我的markAs() 函数如下所示:

markAs(value, step) {
        step.answer = value;
    }

虽然step.answer 更改为done,但按钮的颜色保持不变。

class App extends Component {
   steps = [...some steps];
}

怎么了?

【问题讨论】:

  • 步是一种状态吗?
  • @Rodius steps 是我声明的对象数组
  • 由于您没有使用 React 状态,因此当您创建的自定义属性发生更改时,组件不会重新渲染。如果使用setState,它将强制重新渲染组件。

标签: reactjs


【解决方案1】:

只有当组件的状态发生变化时,才能触发 React 重新渲染。状态可以从props 更改或直接setState 更改更改。组件获取更新后的状态,React 决定是否应该重新渲染组件。

import React, { Component } from 'react';

class MyComponent extends Component {
  constructor(props){
   super(props);
   this.state = {
     step: { answer: '' },
   };
   this.markAs = this.markAs.bind(this);
  }

  markAs() {
   this.setState({ step: { answer: 'done' } });
  }

  render(){
   return (
     <Button
       variant="raised"
       color={(this.state.step.answer === 'done' ? 'primary' : 'default')}
       onClick={this.markAs}
      > Done
      </Button>
   );
  }
}

【讨论】:

    【解决方案2】:

    你需要使用 react 组件state。初始化对应按钮的默认值。并在完成后更改状态。

    constructor(props) {
      super(props)
      this.state = {
      }
      steps.forEach( (item,i) => {
        this.state[i] = 'not done'
      })
    }
    
    renderStep(step,stepId) {
      return (
        <Button
          variant="raised"
          color={this.state[stepId] === 'done' ? 'primary' : 'default')}
          onClick={this.setState({[stepId]:'done'}
        >
          Done
        </Button>
      )
    }
    

    在渲染中你需要这样调用(其中stepId 是步骤数组中的位置)

    <div>
      {renderStep(step,stepId)}
    </div>
    

    【讨论】:

    • answer 是我的steps 数组中step 对象的属性,我无法使用您的解决方案
    • 好的,我为您添加数组处理。检查新版本。但我需要注意,解释如何使用状态等需要解决您的问题,但根据您的需要编写完整的应用程序取决于您。
    猜你喜欢
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 2021-07-07
    相关资源
    最近更新 更多