【问题标题】:How to setstate for the dynamic checkboxes in a loop in react?如何在反应循环中设置动态复选框的状态?
【发布时间】:2019-12-23 07:30:12
【问题描述】:

我正在循环加载复选框。我在设置动态复选框的状态时遇到了困难。

我正在循环加载复选框。我需要设置复选框的状态以使其工作。当我设置状态时,每个复选框都会被选中,所以请给我一个解决方案

组件初始化

const ChildComponent = props =>
  <div key={"comp" + props.number} className="relay-team-list">
      <div className="read-more">
          <a href="#">Team {props.number} - Click to Rename</a>
      </div>
      {
          props.members_arr.length > 0 ? (
              props.members_arr.map((member, i) =>
                  member.position === props.number ? (
                      <div key={"members" + i} className="columns is-mobile list-item" id={"member" + props.number}>
                          <div className="column is-one-third">
                              <img src={require('../images/user.png')} />
                          </div>
                          <div className="column txt-mid-grey relay-team-list-text">
                              <p>{member.members_arr.member_name}</p>
                              <p></p>
                              <span className="check-icon"><input type="checkbox" value="checkedB"
                                  checked={this.state.enabledCheckBox + i}
                                  label={{ children: 'cardreader' + i }}
                                  onChange={this.passMemberID}
                              /></span>

                          </div>
                      </div>
                  ) : ''
              )
          ) : ''
      }
  </div>;

函数

passMemberID = () => {
  this.setState((prevState, props) => ({
    enabledCheckBox: !prevState.enabledCheckBox
  }), () => console.log(this.state.enabledCheckBox))
}

构造函数

constructor(props) {
  super(props);
  this.state = {
    enabledCheckBox: false,
  }
}

我需要为每个复选框设置不同的状态,这样我就可以一个一个地点击它们,现在所有的复选框都会被同时选中

【问题讨论】:

  • 最好在您的状态下使用数组:this.state = {enabledCheckedBoxes: []},并按其索引处理每个复选框:passMemberID = (index) =&gt; () =&gt; {yourlogic}。在您的 UI 中,通过复选框的索引调用 passMemberID。您可以在安装组件后初始化阵列。此外,here is a quick recommendation for cleaning your code
  • @Navid 你的意思是在 UI 中设置为 {()=>this.passMemberID(i)} 像这样?
  • @Navid 我是新来的反应和独自学习的人,请给我一些代码示例
  • @Navid 感谢您提供的想法,我已使用您提供的链接将代码修复为标准级别

标签: javascript reactjs checkbox state


【解决方案1】:

构造函数:

constructor(props) {
  super(props);
  this.state = {
    checkBoxObj: {}
  };
}

组件:

<input type="checkbox" 
     checked = {this.state.checkBoxObj[i] || false}
     onChange={() => this.passMemberID(i)}
/>

功能:

passMemberID = (i) => {
  this.setState({
    checkBoxObj: {
      ...this.state.checkBoxObj, ...{[i]: !this.state.checkBoxObj[i]}
    }
  })
}

【讨论】:

  • 不需要这个value="checkedB"
  • @MorloMbakop 是对的。 value 和 label 根本不需要。我只是把它们从问题中拿出来。我正在进行编辑以删除。
  • @MorloMbakop 我正在使用该值进行不同的验证,感谢大家,我终于找到了一种方法,它有点类似于 Mahanta 的代码,但我使用了数组而不是对象跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-02
  • 2017-06-23
  • 2021-10-31
  • 2019-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多