我正在研究reactjs。我的状态看起来像这样
constructor(props) {
super(props);
this.state = {
open: []
};
}
componentWillReceiveProps(nextProps) {
let {open} = this.state;
for(var i=0;i<nextProps.groupB.length;i++){
open[i]=false;
}
this.setState({open:open})
}
现在我想通过索引访问这些值,所以我尝试这样:
<div className="panel-body">
{this.props.groupB.map((data,index) =>
<div className="panel panel-default">
<Button
onClick={() =>
this.setState({
open: !this.state.open[index]
})}
>
<Glyphicon
glyph={
this.state.open[index]
? 'glyphicon glyphicon-minus'
: 'glyphicon glyphicon-plus'
}
/>
</Button>
</div>
</div>
<Collapse in={this.state.open}>
<Well>//...some code
</Well>
</Collapse>
</div>
我可能在谷歌搜索错误。但没有得到适当的解决方案
最佳答案
制作一个像这样的点击处理程序
clickHandler(e, index) {
let open = [...this.state.open];
open[index] = !open[index];
this.setState({ open });
}
然后像这样调用该点击处理程序...
onClick={e => this.clickHandler(e, index)}
关于javascript - 如何根据状态ReactJS中定义的数组中的索引访问值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45762347/