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;

   

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-09
  • 2021-12-05
猜你喜欢
  • 2022-03-04
  • 2021-10-16
  • 2021-06-22
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案