简体   繁体   中英

call child function from parent in react 16

After upgrading to react 16 I am getting null in console.log(this.child)

My parent component

import EditReview from './partials/editReview'

class VenueDetails extends Component {
  constructor(props) {
    super(props)
    this.child = React.createRef();
  }
  editButtonClick = () => {
    console.log(this.child)
    this.child.current.onEditClick()
  }
  render() {
    return (
      <div>
        <button className="pull-right" onClick={() => this.editButtonClick(review, i)}>edit</button>
        <div className="place-review-text">
          <EditReview {...this.props}/>
        </div>
      </div>
    )
  }
}

My child component

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

  render() {
    return ()
  }
}

export default EditReview

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

Kindly help me

You have to assign the ref:

<EditReview {...this.props} ref={this.child} />

Also, you don't need to use inline arrow function:

onClick={() => this.editButtonClick(review, i)}
// ------^^^^^ not required
// because, you're already using public class method

Just use:

onClick={this.editButtonClick(review, i)}

Define your method like this:

editButtonClick = (review, index) => { // to access review, i

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