組件間通信除了props
外還有onRef
方法,不過React官方文檔建議不要過度依賴ref。
//父組件
import React, { Component } from "react"; import Child from "./Child"; class Dad extends Component { constructor(props) { super(props); this.state = { arr:["暴富","暴瘦"], txt:"我是尼爸爸" } } onRef=(ref)=>{ this.Child=ref; } click=()=>{ this.Child.childFn(); } render() { return ( <div>
<Child onRef={this.onRef}></Child>
<button onClick={this.click}>父組件調用子組件中的方法</button>
</div>
) } } export default Dad; //子組件
import React, { Component } from "react"; class Child extends Component { constructor(props){ super(props); } componentDidMount() { this.props.onRef(this) } childFn=()=>{ console.log("我是子組件中的方法") } render() { return ( <div>
</div>
) } } export default Child;
原理:
當在子組件中調用onRef函數時,正在調用從父組件傳遞的函數。this.props.onRef(this)
這里的參數指向子組件本身,父組件接收該引用作為第一個參數:onRef = {ref =>(this.child = ref)}
然后它使用this.child
保存引用。之后,可以在父組件內訪問整個子組件實例,並且可以調用子組件函數。