父组件:
import React, { Component } from 'react';
import Child from './child2'
class Parents extends Component {
constructor(props) {
super(props);
}
handleCancel = () => {
console.log('父组件的方法被子组件调用了');
}
childClick = () => {
this.child.onShow()
}
render() {
return (
<section>
<button onClick={this.childClick}>父组件调用子组件的函数</button>
<Child handleCancel={this.handleCancel} onRef={(ref) => { this.child = ref }}></Child>
</section>
);
}
}
export default Parents;
子组件:
import React, { Component } from 'react';
class Child extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.props.onRef(this)
}
onShow() {
console.log('子组件的方法被父组件调用')
}
render() {
return (
<section>
<button onClick={() => { this.props.handleCancel() }}>子组件用this.props调用父组件的函数</button>
</section>
);
}
}
export default Child;