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;