【问题标题】:ReactJS not setting class based on expressionReactJS 没有根据表达式设置类
【发布时间】:2018-09-05 17:18:17
【问题描述】:

我实际上是在尝试在用户单击时切换元素上的类。但不幸的是,我的代码只为单个元素设置了类。看起来视图没有为后续点击刷新,即使设置的类也没有删除。但我的商店正在正常更新。

这是我的代码。

class MyInterests extends Component {
    constructor(props) {
      super(props);
      this.state = {selected: []};
    }

    toggleChip(id, index, event){
        const { interestChanged } = this.props;
        let index = this.state.selected.indexOf(id);
        if(index === -1){
            this.state.selected.push(id);
        }else{
            this.state.selected.splice(index, 1);
        }
        interestChanged(this.state.selected);
    }

    render() {
    const {classes, myinterests: { categories, userinterest } } = this.props;
    const getClassNames = (id) => {
        return classNames(classes.chip, {[classes.selected]: (userinterest.indexOf(id) !== -1)});
    }
    return ( 
        /*..... Few element to support styles....*/
          {categories.map((data, index) => {
               return (
                 <Chip
                    key={data._id.$oid}
                    label={data.name}
                    onClick={this.toggleChip.bind(this, data._id.$oid, index)}
                    className={getClassNames(data._id.$oid)}
                  />
              );
       })}
);
  }
}

谁能告诉我这有什么问题或者我怎样才能做到这一点?

【问题讨论】:

    标签: css reactjs react-native react-redux material-ui


    【解决方案1】:

    由于状态是不可变的,你不能在它上面使用.push。 通过使用this.state.selected.push(id),您正在改变状态,因此不会发出对更改做出反应的信号,从而使更改容易受到未来状态更新的影响(请记住,setState 是异步的,并且更改是针对单个操作进行批处理的)。
    看看this 了解如何解决它。 在您的情况下,更新状态的更好方法是这样的:

    // create a copy of the current array
    var selected = this.state.selected.slice();
    // push the new element to the copy
    selected.push(id);
    // replace the current array with the modified copy
    this.setState({ selected: selected });
    

    【讨论】:

    • interestChanged(this.state.selected); 不会改变道具而不是状态?
    猜你喜欢
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    相关资源
    最近更新 更多