简体   繁体   中英

call child function from parent in reactjs

My parent component

import EditReview from './partials/editReview'

class VenueDetails extends Component {
  constructor(props) {
    super(props)
    this.child = React.createRef();
  }
  render() {
    return (
      <div className="place-review-text">
        <EditReview {...this.props}/>
      </div>
    )
  }
}

My child component

class EditReview extends Component {
  onEditClick(review, editIndex) {
    console.log('ppp')
  }

  render() {
    const { handleSubmit, user, pristine, index, commentCrossClick } = this.props
    return (
      <div>
        <Field
          name="content"
          component={renderTextArea}
          className="form-control"
          label="Write your review..."
          rows={2}
        />
      </div>
    )
  }
}

export default EditReview

I need to call onEditClick from the parent component. I tried this but doesn't work.

Kindly help me

Edit

After upgrade I am getting this

Error in ./~/react-dom/lib/ReactServerRendering.js
Module not found: 'react/lib/React' in /home/user/ashish/LTC/lovethesecities-frontend/node_modules/react-dom/lib

After resolving all the errors call child function from parent in react 16

React docs have a example of this using refs

https://reactjs.org/docs/refs-and-the-dom.html

I'm also wondering the use case of wanting to do this, maybe some context could help with an answer?

Try doing it like this:

import EditReview from './partials/editReview'

class VenueDetails extends Component {
  render() {
    return (
      <div className="place-review-text">
        <EditReview ref={Ref => this.child=Ref } {...this.props} />
      </div>
    )
  }
}

and call the function in parent component as this.child.onEditClick(param1,param2)

EDIT1 :

if you have to do it with react 15.x itself what you can do it is create the function in parent and pass it as a prop to child

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