【问题标题】:call child function from parent in react 16在反应 16 中从父级调用子函数
【发布时间】:2018-09-01 08:15:12
【问题描述】:

升级到反应后16我在console.log(this.child)得到null

我的父组件

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>
    )
  }
}

我的子组件

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

  render() {
    return ()
  }
}

export default EditReview

我需要从父组件调用onEditClick。我试过this,但没有用。

请帮帮我

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你必须分配参考:

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

    另外,你不需要使用内联箭头函数:

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

    只需使用:

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

    像这样定义你的方法:

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

    【讨论】:

    • 内联箭头函数,因为我在循环中使用子组件... render() { return () // 它是 null } 它只是为了简化上述问题中的代码
    • 循环不需要内联箭头函数。
    • 即使是为了简化代码,你至少可以显示单行的虚拟内容。当你问下一个问题时不要再这样做了。
    猜你喜欢
    • 1970-01-01
    • 2020-01-22
    • 2019-02-07
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多