【问题标题】:How can I get the values of all sibling input checkboxes in a child component?如何获取子组件中所有同级输入复选框的值?
【发布时间】:2018-11-27 21:05:47
【问题描述】:

我有一个父组件和一个子组件 (Child1) 以及另一个子组件 (Child2)。 Child2 有复选框:

    <input name='val1' id='val1' value='val1' type='checkbox' />
    <input name='val2' id='val2' value='val2' type='checkbox' />

我希望父组件能够获取所有复选框的值(可能是逗号分隔)。我要么想要传递一个处理程序,要么让我的父组件能够读取所有值

【问题讨论】:

  • 传递处理程序是正确的方法。

标签: reactjs


【解决方案1】:

有几种方法可以实现这一点,但最简单的是这样的:

class Child2 extends React.Component {

  onChangeCheckbox(event) {

    // Update state of child2 to capture current check state of checkbox 
    // inputs in Child2
    this.setState({
      [ event.target.name ] : event.target.checked
    }, () => {    

      // Upload the combined/current state of checkbox name/checked pairs 
      // to Parent via onInputClicked callback prop
      this.props.onInputClicked(this.state)
    })

  }

  render() {

    return (<React.Fragment>
      <input name='val1' id='val1' value='val1' type='checkbox'
      onClick={ event => this.onChangeCheckbox(event) } />
      <input name='val2' id='val2' value='val2' type='checkbox'  
      onClick={ event => this.onChangeCheckbox(event) } />
      </React.Fragment>)
  }
}

class Parent extends React.Component {
  render() {

    // Render Child2 with checkbox inputs from Parent and pass onInputClicked
    // prop as a callback
    return (<Child2 onInputClicked={ values => {
      console.log('checkbox values in parent', values)
    } } />)
  }
}

希望有帮助!

【讨论】:

  • 如果 Child2 是无国籍的怎么办?
  • 在这种情况下,您可以直接从复选框的 onClick 处理程序中调用 props.onInputClicked 回调并解析 &lt;Parent /&gt; 中的值 - 您希望我修改答案以证明这一点吗?
  • 不,明白了!我认为这是最好的方法,但不确定。
猜你喜欢
  • 2016-12-31
  • 1970-01-01
  • 2020-01-16
  • 1970-01-01
  • 1970-01-01
  • 2019-10-27
  • 1970-01-01
  • 1970-01-01
  • 2022-07-05
相关资源
最近更新 更多