zoukankan      html  css  js  c++  java
  • 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;
    

       

  • 相关阅读:
    2020/5/18
    2020/5/17
    2020/5/15
    2020/5/13
    2020/5/12
    服务器环境配置五大免费主机系统
    6:运算符
    5:练习题
    4:Python的while循环
    3:Python条件语句
  • 原文地址:https://www.cnblogs.com/VaeVae/p/10383798.html
Copyright © 2011-2022 走看看