2017-01-26 99 views
0

我有這個代碼插入到數組中的checkboks的ID,但如果我禁用它們,它不會刪除它們,我使用更新react-addons更新 任何建議添加/刪除元素與數組與檢查和反應

 constructor(props) { 
     super(props); 
     this.state={ 
      keyGen:[] 
     } 
     } 
     render(){ 
     <form> 
      {this.renderElements()} 
      <input type="submit" value="Save" /> 
     </form> 
     renderElement(){ 
     return this.props.Elements.map((item, index)=>{ 
render(
     <Input name='list' type='checkbox' onClick={()=>this.updateStateList(item.id)} label='Add' className='listTour' /> 
     ) 
     }) 
     } 

     updateStateList(value){ 
     this.setState(update(this.state, {keyGen: {$push:[value]}})) 
     console.log(this.state.keyGen) 
     } 

感謝

+0

這裏http://codepen.io/umgupta/pen/dNVoBg 查看控制檯選項卡中看到工作代碼,如果您取消選中該複選框,它不會刪除該數組中的項目? –

+0

不,只有插入項目 –

+0

我不明白你的問題。 「如果我禁用它們」是什麼意思? –

回答

1

//修改渲染功能是這樣的。

您可以在底部

class UpdateStateDemo extends React.Component { 
     constructor(props) { 
     super(props); 
     this.state={keyGen:[]} 
     } 

     render(){ 
     console.log(this.state) 
     return (
     <form> 
      { 
       this.props.Elements.map((item, index)=>{ 
       return (
        <input 
        key={item} 
        name='list' 
        type='checkbox' 
        onClick={(e)=>this.updateStateList(e,item)} 
        label='Add' 
        className='listTour' /> 
       ) 
      }) 
      } 
      <input type="submit" value="Save" /> 
     </form> 
     ) 
     } 

    updateStateList(e, value){ 
    console.log(e.target.checked) 
    if (e.target.checked){ 
     //append to array 
     this.setState({ 
     keyGen: this.state.keyGen.concat([value]) 
     }) 
    } else { 
     //remove from array 
     this.setState({ 
     keyGen : this.state.keyGen.filter(function(val) {return val!==value}) 
     }) 
    } 
} 
} 
+0

它的工作表示感謝,但它很有趣,爲什麼當我做第一次選擇它顯示空數組,你知道它爲什麼可以是 –

+0

因爲你有一個空狀態的數組集? –

+0

但是,如果用戶只發送一個數據,然後發送空數組,那麼如何解決它 –