react 父組件調用子組件方法、子組件調用父組件方法


我們閑話不多說,直接上代碼

// 父組件
import React, {Component} from 'react';
class Parents extends Component {
    constructor(props) {
        super(props);
        this.state = {
        }
    }
    componentDidMount() {

    }
    
    handleCancel = (e) => {
        console.log('父組件的方法被子組件調用');
    }

    childClick = (e) => {
        this.child.onShow()
    }
    render() {
        return (
            <section>
                <Child onCancel={this.handleCancel} onRef={(ref)=>{ this.child = ref}}></Child>
                <div onClick={this.childClick}>調用子組件的函數</div>
            </section>
        );
    }
}

export default Parents;



// 子組件
import React, {Component} from 'react';
class Child extends Component {
    constructor(props) {
        super(props);
        this.state = {
        }
    }

    componentDidMount() {
        this.props.onRef(this)
    }
    
    onShow(){
        console.log('子組件的方法被父組件調用')
    }

    render() {
        return (
            <section>
                <div onClick={()=>{this.props.handleCancel()}}>子組件用this.props調用父組件的函數</div>
            </section>
        );
    }
}

export default Child;

 


免責聲明!

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



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