Skip to content

Fakin's Blog

  • 首页
  • 前端
    • Vue
    • React
    • JavaScript
    • CSS
  • 技术
    • 织梦教程
  • 模板
    • 织梦模板
    • wordpress主题
  • 资源
  • 日记
  • 友链

React父子组件通信

十二月 1, 2018 by Fakin

React间父子组件通信,非常简单,如果你有点基础,基本上是一看就明白了

1、父子组件通信

如果你会vue,那么你就应该知道,vue是通过props给子组件传递参数的。而React也是通过props传递的,但是更加的简单和容易理解!

父组件:
import List from '../../common/list/list'
//···
render(){
return(
<div className="article">
     { this.props.list.map((item, index) => {
          return <List article={item} key={index} index={index}
                   deleteItem={this.handleListDelete.bind(this)} />
          })
      }
</div>
)
}

在render的List组件中,和自定义属性一样article={item}即可

子组件:
render() {
   return (
            <div className="article-list">
                <Link to={this.props.isSearch ? {
                    pathname: this.props.article.url,
                } : `/detail/${this.props.article.id}`}
                      target='_blank'>
                    <div className="article-content">
                        <h3 className="article-title">
                            {this.props.article.title}
                        </h3>
                    </div>
                </Link>
            </div>
   )
}

然后直接在子组件中的props中就会有一个article对象。

2、子父组件通信

子父组件通信是,通过子组件调用父组件的方法,传递参数进行通信的。也很简单!

父组件:
import List from '../../common/list/list'
//···
async handleListDelete(index) {
        //index来自子组件的this.props.index
        let list = [...this.props.list];
        this.props.delNewsList(index);
        if (list.length === 1) {
            this.props._isLoading(true);
            await this.props.loadMoreList()
            this.props._isLoading(false);

        }
}
render(){
return(
<div className="article">
     { this.props.list.map((item, index) => {
          return <List article={item} key={index} index={index}
                   deleteItem={this.handleListDelete.bind(this)} />
          })
      }
</div>
)
}

和上面一样,但是这次重点是在deleteItem={this.handleListDelete.bind(this)},这里把父组件的方法this.handleListDelete传递过去了。

子组件:

class children extends Component { handleDelete() { this.props.deleteItem(this.props.index) } }

因为父组件是通过deleteItem={this.handleListDelete.bind(this)}把方法传递给子组件的,所以子组件中this.props.deleteItem()这个方法映射的就是父组件的方法。
这样我们就可以在子组件中调用父组件的handleListDelete方法,然后进行传参,父组件就可以获得参数了!

Post navigation

上一篇:

Redux在React中最佳实践方法

下一篇:

React.v16版本中生命周期的使用及建议

最近文章

  • React中Refs学习(二)
  • vue轮播组件-vue-fakin-slider
  • React中Refs学习(一)
  • Reudx学习(二)
  • 2018年终总结
  • 浅谈javascript执行环境、作用域
  • Redux学习(一)
  • reduce函数探索

最近评论

  • 五福吧发表在《2018年终总结》
  • hqweay发表在《2018年终总结》
  • Fakin发表在《Redux学习(一)》
  • 演员发表在《Redux学习(一)》
  • Fakin发表在《express+mongodb个人博客开发》

更新日历

2019年二月
一 二 三 四 五 六 日
« 1月    
 123
45678910
11121314151617
18192021222324
25262728  
© 2019 Fakin's Blog | WordPress Theme by SuperbThemes | 蜀ICP备16017838号-2