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传递到父组件,父组件直接调用子组件的方法。

猜你喜欢

转载自www.cnblogs.com/luziluck/p/10344719.html
今日推荐