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

2020-04-20  本文已影响0人  KK_boy
import React, {Component} from 'react';

export default class Parent extends Component {
   render() {
       return(
           <div>
               <Child onRef={this.onRef} />
               <button onClick={this.click} >click</button>
           </div>
       )
   }

   onRef = (ref) => {
       this.child = ref
   }

   click = (e) => {
       this.child.myName()
   }

}

class Child extends Component {
   componentDidMount(){
       this.props.onRef(this)
   }

   myName = () => alert('kaysen')

   render() {
       return ('hello world!')
   }
}
上一篇 下一篇

猜你喜欢

热点阅读