gpt4 book ai didi

css - ReactJS 不根据表达式设置类

转载 作者:太空宇宙 更新时间:2023-11-04 07:29:56 24 4
gpt4 key购买 nike

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

这是我的代码。

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)}
/>
);
})}
);
}
}

谁能告诉我这有什么问题或者我该如何实现?

最佳答案

因为状态是不可变的,你不能在它上面使用.push。通过使用 this.state.selected.push(id),你正在改变状态,因此 不发出信号对变化使用react 使变化容易受到 future 状态更新的影响(记住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 });

关于css - ReactJS 不根据表达式设置类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49510488/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com