【问题标题】:Access other component refs from within component从组件内访问其他组件引用
【发布时间】:2025-12-11 13:55:01
【问题描述】:

我正在寻找一种让两个组件相互通信的方法。我只是想要它,以便在选中或取消选中 <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'/>

如何从 &lt;InputCheckboxAll&gt; 组件中选择 dom 上带有 masterCheckbox 的所有引用?

【问题讨论】:

    标签: javascript reactjs components


    【解决方案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>
                )
            }
        })
    

    【讨论】:

    • 非常感谢,太棒了!一个问题是&lt;InputCheckbox&gt; 需要getInitialState,其中checked 为假,但这使得它无法自行检查。
    • 我检查了getInitialState checkedthis.props.checked 的值,它解决了这个问题。
    • 假设所有三个 &lt;InputCheckbox&gt; 都已检查,如何将 &lt;InputCheckboxAll&gt; 的值更改为已检查?
    • 您可以将检查处理程序传递给 InputCheckbox 并为每个 id 设置状态(为每个添加 id)并添加 allInputChecked 并传递给 InputCheckedAll。
    • 您介意解释一下“每个 id 都有状态”是什么意思吗?