如何在React中将多个复选框的值存入数组?

5
如何在React JS中将多个复选框的值存储到数组中?这是我从API获取的动态目的地列表。我想使用一个数组将其发送到后端。
{
  this.state.destination.length > 0 ? (
    this.state.destination.map((destination, index) => (
      <div className="col-md-3">
        <div class="pretty p-default">
          <input type="checkbox" name="dest" value={index} onClick={event => this.handleDestination(event)} />
          <div class="state p-primary">
            <label>{destination.dest_name}</label>
          </div>
        </div>
      </div>
    ))
  ) : (
    <div>
      <label>
        <b>No results found ! </b>{' '}
      </label>
    </div>
  );
}



handleDestination(event) {

    const options=this.state.options
    let index
    if(event.target.checked){
      options.push(+event.target.value)
    }
    else{
      index=options.indexOf(+event.target.value)
      options.splice(index,1)
    }
    this.setState({ options:options})

}

https://github.com/ziad-saab/react-checkbox-group ?请返回已翻译的文本。 - Josh Lin
2个回答

4
你可以使用一个额外的参数 - 已选元素的索引,将你的 handleDestination 方法与之绑定: this.handleDestination.bind(this, index) 示例:fiddle
class Example extends React.Component {
  ...      
  onToggle(index, e){
    let newItems = this.state.items.slice();
    newItems[index].checked = !newItems[index].checked

    this.setState({ items: newItems })
  }

  render() {
    return (
        <div>
          <ul>
          {this.state.items.map((item, i) =>
            <li key={i}>
              {item.text}
              // binding an index
              <input type="checkbox" onChange={this.onToggle.bind(this, i)} />
            </li>
          )}
          </ul>
        <br/>
          // filter by checked element
          You checked: {JSON.stringify(this.state.items.filter(item => item.checked))}
        </div>
    )
  }
}

更新 针对你的代码 - 修改

this.handleDestination(event)

this.handleDestination.bind(this, index)
                   ^^^^^^^^^^^^^^^^^

然后修改一个handleDestination方法,与我上面所做的类似:
handleDestination(index, event){
  console.log(index) // checked element index
  console.log(this.props.destination[index]) // your checked element
  ...
}

希望这能有所帮助。


我明白了,我的新函数是这样的。它运行良好,但是值没有输出,数组的索引出现了。我该如何更改?这是我的新函数。 - Gu Gue
我再次更新了我的问题。让我检查一下我的handleDestination函数。我不想获得数组的索引,而是想要值。我该如何修复这个问题? - Gu Gue
@GuGue 你看过我的示例代码了吗?我更新了我的回答。 - The Reason

1

这是我在项目中使用的类似模式。你可以在这里参考。

 state = {
    form: {
      companyType: '',
      services: [],
      name: '',
      surname: '',
      email: '',
      concepts: [],
      technologies: [],
    },
  };


public handleChange = (event: any) => {
    const { name } = event.target;
    const checkedArr = [];
    let value;
    if (event.target.type !== 'checkbox') {
      value = event.target.value;
    } else {
      const checkeds = document.getElementsByTagName('input');
      for (let i = 0; i < checkeds.length; i++) {
        if (checkeds[i].checked) {
          checkedArr.push(checkeds[i].value);
        }
      }
      value = checkedArr;
    }

    const { form } = this.state;
    form[name] = value;

    this.setState({ form });
  };

我正在把复选框的值存入数组中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接