简体   繁体   English

在反应16中从父级调用子级函数

[英]call child function from parent in react 16

After upgrading to react 16 I am getting null in console.log(this.child) 升级到反应16后,我在console.log(this.child) null

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. 我需要从父组件调用onEditClick 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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