如果未使用React检查,则从数组中删除

时间:2016-07-21 22:31:03

标签: javascript arrays reactjs

选中后,添加到阵列。取消选中后,从阵列中删除。我的代码可以正常工作,但null代替了它。我需要完全删除它。怎么样?

...

getInitialState: function(){
  return{
    email: this.props.user,
    product: []
  }
},

_product: function(){
  if (this.refs.opt1.checked) {
      var opt1 = this.refs.opt1.value;
  } else {
    this.setState({ product: this.state.product.filter(function(_, i) { return i  }) });
  };

  if (this.refs.opt2.checked) {
    var opt1 = this.refs.opt2.value;
  } else {
    this.setState({ product: this.state.product.filter(function(_, i) { return i }) });
  };
  var array = this.state.product.concat([opt1]);
  this.setState({
      product: array
  });
},

render: function(){
  return(
   <div><input ref="opt1" type="checkbox" value="foo" onClick={this._product}/></div>
  )
}

...

1 个答案:

答案 0 :(得分:0)

我认为如果您保留一系列选项会更容易管理,其中每个选项都有选中的属性。有点像:

...
constructor(props) {
  super(props);

  this.toggleOption = this.toggleOption.bind(this);
}

getInitialState(){
  return {
    email: this.props.user,
    options: [
      { value: 'Foo1', otherProperty: 'something', checked: false },
      { value: 'Foo2', otherProperty: 'something', checked: false },
    ],
  }
}

toggleOption(index) {
  // Clone the options array
  const options = this.state.options.slice();

  // Toggle the option checked property
  if(options[index]) {
    options[index].checked = !options[index].checked;
  }

  // Update the component state
  this.setState({
    options
  });
}

getSelectedOptions() {
  // Use this to grab an array of selected options for whatever reason...
  return this.state.options.filter(option => option.checked);
}

render: function(){
  return(
    <div>
      { this.state.options.map((i, option) => {
        <input type="checkbox" checked={option.checked} value={option.value} onClick={() => this.toggleOption(i) } />
      }) }
    </div>
  )
}
...