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组件.只有各自子组件可以操作

猜你喜欢

转载自www.cnblogs.com/ljbcnblogs/p/9942351.html