react 父组件调用子组件的方法

class Parent extends React.Component {
  render() {
    return (
      <div className="parent">
        {/* 把子组件实例(ref)传递给this.child */}
        <Child
          onRef={ref => {
            this.child = ref
          }}
        />
        {/* 执行子组件实例的方法 */}
        <button onClick={this.child.speak}>click</button>
      </div>
    )
  }
}
class Child extends React.Component {
  constructor(props) {
    super(props)
    // 将当前实例(this)传递给父组件
    props.onRef(this)
  }
  speak() {
    alert('hello there')
  }
  render() {
    return <div className="child">child</div>
  }
}
posted @ 2019-02-27 16:23  heylight  阅读(206)  评论(0)    收藏  举报