我是 React 的新手,很难为我的问题找到合适的答案。我有一个包含多个按钮 (23) 的列表,我想为每个被单击的按钮添加一个 .active 类。我将按钮“值”保存在状态数组中供以后使用。因此,可以有多个具有事件类的按钮,没有具有相应类的按钮。
class DistrictModal extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedDistricts: []
}
}
addDistrictToList = (e) => {
this.setState(prevState => ({
selectedDistricts: [...prevState.selectedDistricts, e]
}));
}
render() {
<div className="list-group">
<button type="button" onClick={() => this.addDistrictToList("1")} > 1. bezirk </button>
<button type="button" onClick={() => this.addDistrictToList("2")} > 2. bezirk </button>
<button type="button" onClick={() => this.addDistrictToList("3")} > 3. bezirk </button>
</div>
}}
最佳答案
试试这个:
<button type="button" onClick={() => this.addDistrictToList("1")}
className={this.state.selectedDistricts.includes(1) ? 'active' : ''}> 1. bezirk </button>
如果列表包含值“1”,则添加类 active
关于javascript - 单击时将类添加到 ReactJS 中的多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59664229/