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 }
上面點擊按鈕,會彈出子組件的輸出.其實也很簡單. 就是一個簡單的方法,把子組件的參數回傳到父組件中,並且賦值給子組件的一個實例方法.
有些場景是可能需要公用的,在父組件中統一調用子組件的方法.比如antd的form組件.只有各自子組件可以操作
