简体   繁体   中英

Remove from array if unchecked with React

When checked, add to array. When unchecked, remove from array. My code below works but null is placed in its place. I need to remove it completely. How?

...

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>
  )
}

...

I think it would be easier to manage if you kept an array of options, where each option has a selected property. Something along the lines of:

...
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>
  )
}
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM