从组件内访问其他组件引用

时间:2015-09-17 19:04:20

标签: javascript reactjs components

我正在寻找一种让两个组件相互通信的方法。我只是想要它,以便在选中或取消选中<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>组件中选择dom上masterCheckbox的所有引用?

1 个答案:

答案 0 :(得分: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>
            )
        }
    })
相关问题