简体   繁体   中英

React: How to use ref of a child component in a parent component?

I will explain my self better here, for example i have 2 components 1 will be Modal 2 will be Form.

Modal will have state, functions that it will pass to Form. Form should have it's own ref. that Modal can use. I try to illustrate:

class Modal extends Component {

 handleSubmit(e) {
  e.preventDefault();
  if ($(this.refs.form).form('is valid') {
  //Do something...
  }
 }

 render() {
  return (
   <Form ref="form" handleSubmit={::this.handleSubmit} />
  )
 }
}

class Form extends Component {
 render() {
  return (
   <form onSubmit={this.props.handleSubmit} ref={this.props.ref}>
    //Inputs go here...
   </form
  )
 }
}

Now the ref we assign in the Modal doesn't work ... we can use the form ref only in the Form component.... how can i share them ??

If you really need this:

class Modal extends Component {

 handleSubmit(e) {
  e.preventDefault();
  if(this._form._inner.state.isValid) {
   //Do something...
  }
 }

 render() {
  return (
   <Form ref={c => this._form = c} handleSubmit={this.handleSubmit} />
  )
 }
}

class Form extends Component {
 state = {
   isValid: false
 }

 render() {
  return (
   <form onSubmit={this.props.handleSubmit} ref={c => this._inner = c}>
    //Inputs go here...
   </form>
  )
 }
}

But you should try to build components with callbacks and do stuff there.

Better try something like this:

class Modal extends Component {

 handleSubmit(isValid) {
   //... do stuff
 }

 render() {
  return (
   <Form handleSubmit={this.handleSubmit} />
  )
 }
}

class Form extends Component {

 constructor(props) {
  super(props);
  this.onSubmit = this.onSubmit.bind(this);
 }

 validate() {
   // ... validate
   this.setState({ isValid: ... });
 }

 onSubmit() {
  const { handleSubmit } = this.props;


  if(handleSubmit) {
   handleSubmit(this.state.isValid);
  }
 }

 render() {
  return (
   <form onSubmit={this.onSubmit}>
    //Inputs go here...
   </form>
  )
 }
}

And you should rly get rid of jQuery if you using React. Bit of overload..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM