2016-07-21 7 views
0

これをチェックすると、配列に追加されます。チェックを外すと、配列から削除されます。下のコードは動作しますが、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> 
) 
} 

... 
+0

このフィルタ機能の意味はなんですか?最初の要素を削除しますか?また、チェックボックスでチェックするのではなく、値を使うのはなぜですか? – OriolBG

+0

@OriolBGそれは 'arr.slice(1)'と書かれた奇妙な方法です。 OPも、関数の最後に 'setState'を呼び出しています。したがって、前の' setState'呼び出しは上書きされています。オプションがチェックされていなければ 'opt1'は定義されません – azium

+0

' this.setState {製品:this.state.product.filter(function(i){return i!== null})}); '' null'はまだそこにあります – Sylar

答えて

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> 
) 
} 
... 
関連する問題