react父組件和子組件之間相互調用方法


父組件:

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;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM