2017-05-15 2 views
-1

私はリアクションを学んでおり、簡単なToDoリストを構築しています。私は今、私は、チェックボックスをクリックして、1Reactjsは、チェックされた入力に基づいてオブジェクトのプロパティの状態を変更します。

にプロパティ doneの状態を変更したいマイtodolistのコンポーネントは、このマップ機能を持っている私の initialState

getInitialState:function(){ 
    return { 
     items: [ 
      { 
       text:"Buy Fish", 
       key: "1", 
       done: 0 
      } 
      ] 
     } 
}, 

var listItem = this.props.items.map((item, index)=>{ 
     return <li key={item.key}> <input type="checkbox" onChange={(e)=>{this.props.onChange(item.key, e)}} /> <span onClick={()=>{this.props.editItem(item.text)}}>{item.text}</span> <button onClick={()=>this.props.removeItem(item.key)}>x</button> </li> 
    }); 

をこのオブジェクトを持っています

onChange小道具は関数につながっています

itemDone:function(index, e){ 
    var myArray = this.state.items; 
    var a = e.target.checked; 
    console.log(index); 
}, 

値を0から1に変更する正しい方法は何ですか?

答えて

1

onChangeメソッドにインデックスを渡すことができます。

var listItem = this.props.items.map((item,index)=>{ 
      return <li key={item.key}> <input type="checkbox" onChange={(e)=>this.props.onChange(index,e)} /> <span onClick={()=>{this.props.editItem(item.text)}}>{item.text}</span> <button onClick={()=>this.props.removeItem(item.key)}>x</button> </li> 
     }); 

とget特定持つアイテムとindex

itemDone:function(index,e){ 
    var myArray = this.state.items; 
    var a = e.target.checked; 
    console.log('item': this.state.items[index]); 
}, 
0

インデックスを渡して、同じオブジェクトを編集します。また、spread operatorを使用して、アイテム配列の新しいオブジェクトインスタンスを作成します。myArrayは、不変オブジェクト状態アイテム自体を参照します。

var listItem = this.props.items.map((item, index)=>{ 
      return <li key={item.key}> <input type="checkbox" onChange={()=>this.props.onChange(index)} /> <span onClick={()=>{this.props.editItem(item.text)}}>{item.text}</span> <button onClick={()=>this.props.removeItem(item.key)}>x</button> </li> 
     }); 


itemDone:function(index){ 
    var myArray = [...this.state.items]; 
    if(myArray[index].done == 0) { 
      myArray[index].done = 1; 
    } else { 
      myArray[index].done = 0; 
    } 
    this.setState({items: myArray}) 
}, 
関連する問題