• 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;
  • 相关阅读:
    7-36 复数四则运算
    7-35 有理数均值
    7-34 通讯录的录入与显示
    7-33 有理数加法
    7-32 说反话-加强版
    POJ-2524-Ubiquitous Religions
    POJ-2406-Power Strings
    HDU-1072-Nightmares
    POJ-1961-Period(ZOJ-2177)
    POJ-1961-Period(ZOJ-2177)
  • 原文地址:https://www.cnblogs.com/houjl/p/11165777.html
Copyright © 2020-2023  润新知