React父組件調用子組件的方法


 1 import React, {Component} from 'react';
 2 
 3 export default class Parent extends Component {
 4     render() {
 5         return(
 6             <div>
 7                 <Child onRef={this.onRef} />
 8                 <button onClick={this.click} >click</button>
 9             </div>
10         )
11     }
12 
13     onRef = (ref) => {
14         this.child = ref
15     }
16 
17     click = (e) => {
18         this.child.myName()
19     }
20 
21 }
22 
23 class Child extends Component {
24     componentDidMount(){
25         this.props.onRef(this)
26     }
27 
28     myName = () => alert('xiaohesong')
29 
30     render() {
31         return ('woqu')
32     }
33 }

上面點擊按鈕,會彈出子組件的輸出.其實也很簡單. 就是一個簡單的方法,把子組件的參數回傳到父組件中,並且賦值給子組件的一個實例方法.

有些場景是可能需要公用的,在父組件中統一調用子組件的方法.比如antdform組件.只有各自子組件可以操作


免責聲明!

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



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