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

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()函数验证所有子输入。

我怎样才能做到这一点?

提前致谢

最佳答案

使用ref使用新的React.cloneElement道具克隆整个孩子。提交时,使用ref访问孩子的方法。

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

希望这可以帮助!



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>

07-24 09:38
查看更多