react父元件呼叫子元件方法
阿新 • • 發佈:2019-02-11
把子元件的引數回傳到父元件中,並且賦值給子元件的一個例項方法.
參考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')
}
}