通点击父组件按钮调用子组件的方法
父组件:
import React, {Component} from ‘react‘; import ChildComponent from ‘./child‘; export default class ParentComponent extends Component { render() { return( <div> <ChildComponent onRefChild={this.onRefChild} /> <button onClick={this.clickParent.bind(this)} >{‘点击‘}</button> </div> ) } onRefChild = (ref) => { this.child = ref } clickParent = (e) => { this.child.childMethods() } }
子组件:
import React, {Component} from ‘react‘; export default class ParentComponent extends Component { componentDidMount(){ this.props.onRefChild(this) } childMethods = () => alert(‘子组件被执行了‘) render() { return (<div>我是子组件</div>) } }
原文地址:https://www.cnblogs.com/0828-li/p/11011601.html
时间: 2024-10-25 22:18:22