父组件中使用子组件的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import React, { Component, Fragment } from 'react';
class Child extends Component {
componentDidMount() {
this.props.onRef(this);
}
testEvent = () => {
console.log('我被触发了');
}
render() {
return (
'我是子组件'
)
}
}
export default class Parent extends Component {
onRef = (ref) => {
this.child = ref;
}
handleClick = () => {
this.child.testEvent();
}
render() {
return (
<Fragment>
<Child onRef={this.onRef} />
<button onClick={this.handleClick}>click</button>
</Fragment>
)
}
}