react 中子组件调用父组件的方法


1.在父组件中定义方法,并绑定在子组件上

// 在子组件中调用父组件中的方法
import React,{Component} from 'react';
import Child from './child'

class Parent extends Component{
    constructor(props){
        super(props);
        this.fun=this.fun.bind(this);
    }
    fun(){
        console.log('你调用了父组件的方法')
    }
    render(){
        return (
            <div>
                <Child getFun={this.fun}></Child>
            </div>
        )
    }
}

export default Parent;

  

2.在子组件中通过this.props来调用父组件中的方法、

// 在子组件中调用父组件中的方法
import React,{Component} from 'react';

class Child extends Component{
    constructor(props){
        super(props);
        console.log(this.props,'0000000000000000')
    }
    render(){
        return(
            <div>
                child
                <button onClick={()=>{console.log('你点击了按钮');this.props.getFun()}}>点击</button>
            </div>
        )
    }
}

export default Child;

   

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM