【问题标题】:reactjs parent trigger child componentreactjs父触发子组件
【发布时间】:2017-03-03 14:49:12
【问题描述】:

我有一个父组件,它基本上是一个表单。

export default class Parent extends Component{
  submitInput(event){
    ...call Children
  }

  render(){
    return(
     <div>
      <form className="form-horizontal"  onSubmit= {this.submitInput.bind(this)}>
       {this.props.children}
       <button type="submit">Submit</button>
    </div>
  </form>
</div>);
 }}

孩子可以是不同类型的输入,所有这些都具有一个名为 validate() 的通用函数。

这是一个孩子的例子

export default class Child extends Component{

validate(){
    ..validate stuff
 }


render(){
  return(
      <div className="form-group">
              <textarea ref={this.props.name} />
      </div>
 );
}
}

在提交父组件时,我想使用它们的 validate() 函数验证所有子输入。

我该怎么做?

提前致谢

【问题讨论】:

    标签: javascript forms reactjs components


    【解决方案1】:

    使用React.cloneElement 使用新的ref 属性克隆整个孩子。在提交时使用refs 访问孩子的方法。

    请参见下面的示例。如果需要更多详细说明,请发表评论。

    希望这会有所帮助!

    class Form extends React.Component{
      submitInput(){
        this.childrenClone.forEach((el) => {
          var r = el.ref //use the ref to access the child's methods
          this.refs[r].validate()
        })
      }
      
      render() {
        this.childrenClone = React.Children.map(this.props.children,
         (child) => React.cloneElement(child, {
           ref: Math.random().toString(36).slice(-5) //add a random string as a ref
         })
        )
        
        return <div>
          <form className="form-horizontal"  onSubmit={this.submitInput.bind(this)}>
           {this.childrenClone}
           <button type="submit">Submit</button>
           </form>
        </div>
      }
    }
    
    
    class Child extends React.Component{
      validate(){
        console.log('validate textarea') //on validate log this
      }
      
      render() {
        return <div className="form-group">
              <textarea />
          </div>
      }
    }
    
    class ChildInput extends React.Component{
      validate(){
        console.log('validate Input') //on validate log this
      }
      
      render() {
        return <div className="form-group">
              <input type="text" />
          </div>
      }
    }
    class Parent extends React.Component{
      render(){
        return <Form>
          <Child/>
          <Child/>
          <ChildInput/>
          <ChildInput/>
        </Form>
      }
    }
    
    ReactDOM.render(<Parent/>, document.getElementById('app'))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="app"></div>

    【讨论】:

      猜你喜欢
      • 2020-04-16
      • 1970-01-01
      • 2021-06-11
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      • 2019-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多