zoukankan      html  css  js  c++  java
  • React对比Vue(04 父子组件的通信 )

    跟vue差不多 都是props,但是react里面不仅可以给子组件传值,还可以传方法,MD尽然还可以把自己传给子组件,(卧槽vue可没有这个啊 )  vue的传递值差不多,传方法就不用了,子组件可以掉父组件的方法,父组件也可以直接调用子组件的方法,this.$parents.方法名

    react直接传值

    <Header title={this.state.title} />

    子组件 直接调用<h2>{this.props.title}</h2>

    传递方法,<Header title={this.state.title}  run={this.run}  />

    子组件  <button onClick={this.props.run}>调用news父组件的run方法</button>

    传递父组件自己

    <Header title={this.state.title} run={this.run} news={this} />

    子组件 <button onClick={this.props.news.getData}>获取news组件的getData方法</button>

    子组件也可以这么写<button onClick={this.getNews}>获取整个news组件实例</button>

    getNews=()=>{

    this.props.news.getData();

    }

    、、这里的news属性自己随便写什么名字,但是子组件使用得保持一致

    父组件获取子组件的方法:

    /*
    父组件主动获取子组件的数据

    1、调用子组件的时候指定ref的值 <Header ref='header'></Header>

    2、通过this.refs.header 获取整个子组件实例 (dom(组件)加载完成以后获取 )
    */

    //alert(this.refs.footer.state.msg); //获取子组件的数据

     <Footer  ref='footer'/>

    父组件一个按钮点击事件--》里面写this.refs.footer.run();就可以获取整个子组件实例了

     *********************************************************************************************************************************************************************************

    设置组件的默认值还有类型,vue的看我写的文章

    注意默认pros和类型都在class的同级,然后就是类型要先引入,有一个地方是小写的propTypes ,差不多了

  • 相关阅读:
    vs15
    Areas(区域)
    池编程技术
    MyBitis(iBitis)系列随笔之五:多表(一对多关联查询)
    MyBatis学习总结(五)——实现关联表查询
    Mapper映射语句高阶应用——ResultMap
    mysql中的null字段值的处理及大小写问题
    spring-boot支持双数据源mysql+mongo
    No resource identifier found for attribute 'showAsAction' in package 'android'
    No resource found that matches the given name 'Theme.AppCompat.Light'.
  • 原文地址:https://www.cnblogs.com/myfirstboke/p/10486336.html
Copyright © 2011-2022 走看看