美文网首页
React父组件调用子组件的方法

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

作者: KK_boy | 来源:发表于2020-04-20 16:24 被阅读0次
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!')
   }
}

相关文章

网友评论

      本文标题:React父组件调用子组件的方法

      本文链接:https://www.haomeiwen.com/subject/rvbdihtx.html