react 父组件调用子组件方法

父组件:

import React from 'react';
import Zi from './zi.js'

class Parentcom extends React.Component{
constructor(props){
super(props);
this.state={

}
}

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

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


render(){
return (
<div>
<Zi onRef={this.onRef} />
<button onClick={this.click} >click</button>
</div>
)
}
}
export default Parentcom

 

子组件:

import React from 'react';

class Zi extends React.Component{
constructor(props){
super(props);
this.state={

}
}

componentDidMount(){
this.props.onRef(this)
}

myName = () => alert('xiaohesong')

render(){
return (
<div></div>
)
}
}
export default Zi

 

原理是:把子组件的this传递到父组件,父组件直接调用子组件的方法。

posted on 2019-02-01 08:37  luziluck  阅读(436)  评论(0编辑  收藏  举报

导航