2015-09-17 45 views
0

我正在尋找兩種組件互相通話的方式。我只是想要它,以便當<InputCheckboxAll/>被選中或未選中時,它將檢查或取消選中所有<InputCheckbox/>組件。從組件內部訪問其他組件參考

var InputCheckboxAll = React.createClass({ 
    render: function() { 
    return (
     <input type='checkbox' {...this.props}/> 
    ) 
    } 
}) 

var InputCheckbox = React.createClass({ 
    render: function() { 
    return (
     <input type='checkbox' {...this.props}/> 
    ) 
    } 
}) 

<InputCheckboxAll ref='masterCheckbox'/> 
<InputCheckbox masterRef='masterCheckbox'/> 
<InputCheckbox masterRef='masterCheckbox'/> 
<InputCheckbox masterRef='masterCheckbox'/> 

如何從<InputCheckboxAll>組件我可以選擇與masterCheckbox的DOM所有裁判中?

回答

1

將處理程序傳遞給InputCheckboxAll並將狀態傳遞給InputCheckbox。

var InputCheckboxAll = React.createClass({ 
     handleChange: function(event) { 
      this.props.handleChange(event); 
     }, 
     render: function() { 
     return (
      <input type='checkbox' {...this.props} onChange={this.handleChange} /> 
     ) 
     } 
    }) 

    var InputCheckbox = React.createClass({ 
     render: function() { 
      var checkedValue = this.props.allChecked ? true : this.state.checked; 
     return (
      <input checked={checkedValue} type='checkbox' {...this.props}/> 
     ) 
     } 
    }) 

    var CheckMaster = React.createClass({ 
     getInitialState: function() { return {allChecked: false}; }, 
     handleChange: function(event) { 
      this.setState({allChecked: event.target.value}); 
     }, 
     render: function() { 
      return (
       <div> 
        <InputCheckboxAll handleChange={this.handleChange}/> 
        <InputCheckbox allChecked={this.state.allChecked}/> 
        <InputCheckbox allChecked={this.state.allChecked}/> 
        <InputCheckbox allChecked={this.state.allChecked}/> 
       </div> 
      ) 
     } 
    }) 
+0

感謝一堆,這太棒了!一個問題是''InputCheckbox>'需要'getInitialState',其中'checked'爲false,但是這使得它自己無法檢查。 – ThomasReggi

+0

我將'getInitialState'' checked'的值檢查爲'this.props.checked'並修復了問題。 – ThomasReggi

+0

假設我們都檢查了所有三個「」,我怎樣才能改變''的值來檢查? – ThomasReggi