javascript - 如何根据状态ReactJS中定义的数组中的索引访问值

标签 javascript reactjs ecmascript-6

我正在研究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/

相关文章:

javascript - 在 Rails 4.0.1 中添加页面特定的 JS

javascript - appcelerator alloy应用中的内存管理

javascript - React Router 在 localhost 和 Heroku 上的行为不同

javascript - 比较断言中的函数输出类型

reactjs - React 构造函数中的 : Setting this. 属性...? (不试图改变 Prop )

javascript - 将全局导入模块模式转换为 ES6 模块

javascript - @media 用于 Javascript 文本动画

javascript - .appendChild() 中的多个变量和文本

reactjs - 该电子邮件已存在验证

reactjs - 映射对象数组状态时如何重新渲染 react 组件