react 父組件調用子組件中的方法


組件間通信除了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保存引用。之后,可以在父組件內訪問整個子組件實例,並且可以調用子組件函數。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM