版权声明:本文为原创文章,转载请注明出处! https://blog.csdn.net/Fakin/article/details/85124843
React间父子组件通信,非常简单,如果你有点基础,基本上是一看就明白了
本文为系列文章首发于我的博客:https://www.fakin.cn
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>
)
}
子组件直接this.props.xxxx
(其中xxxx为你在父组件中给子组件传递的article={item}
)
然后在子组件中的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
方法,然后进行传参,父组件就可以获得参数了!