把子组件的参数回传到父组件中,并且赋值给子组件的一个实例方法.
参考React中文网: http://www.css88.com/react/docs/refs-and-the-dom.html
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(){
//必须在这里声明,所以 ref 回调可以引用它
this.props.onRef(this)
}
myName = () => alert('我的名字')
render() {
return ('lalalala')
}
}