首页 > 其他 > 详细

react父组件和子组件之间相互调用方法

时间:2020-11-24 11:14:10      阅读:33      评论:0      收藏:0      [点我收藏+]
父组件:

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;

 

react父组件和子组件之间相互调用方法

原文:https://www.cnblogs.com/plBlog/p/14028842.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!