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;
    

       

  • 相关阅读:
    毕设进度21
    毕设进度20
    Javascript高级程序设计第三版-笔记
    前端踩过的坑
    thinkphp笔记
    PHP 发邮件《转》
    smarty笔记
    jquery笔记
    JS笔记
    php万年历
  • 原文地址:https://www.cnblogs.com/VaeVae/p/10383798.html
Copyright © 2011-2022 走看看