我們都知道在 react中,若要在父組件調用子組件的方法,通常我們會采用在父組件定義一個方法,作為props轉給子組件,然后執行該方法,可以獲取到子組件傳回的參數以得到我們的目的。
顯而易見,這個執行是需要去主動觸發的。
那有沒有一種方式,方法在子組件定義好,可以直接在父組件去調用呢?
答案是必然的。
上代碼^ - ^
import React, {Component} from "react";
import { Button } from "antd";
//父組件
export default class Parent extends Component {
render() {
return(
<div>
<p>這是父組件</p>
<Child triggerRef={this.bindRef} />
<Button type="primary" onClick={this.btnClick} >click</Button>
</div>
)
}
bindRef = ref => { this.child = ref }
btnClick = () => {
this.child.getValuefromChild()
}
}
//子組件
class Child extends Component {
componentDidMount(){
this.props.triggerRef(this)
}
//這是子組件的方法
getValuefromChild = () => console.log("this is child value.")
render() {
return <div>這是子組件</div>
}
}
是不是瞬間就風清月朗了~~
