在不是用redux的情况下,使用子(孙)组件上的方法,或者属性
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>
)
}
//定义一个拿子组件返回值this的函数
onRef = (ref) => {
this.child = ref
}
//调用处理函数
click = (e) => {
this.child.myName()
}
}
class Child extends Component {
componentDidMount(){
//通过pros接收父组件传来的方法
this.props.onRef(this)
}
myName = () => alert('子组件fn')
render() {
return ('ch')
}
}
作者:薛定喵的谔
链接:https://juejin.im/post/5c86c7d8f265da2de970b610
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。