在项目开辟的过程当中,跟着运用功用庞杂度的增添和组件条理分别的需求,组件之间的通讯越来越多,
我大抵以为组件之间的通讯分为3种:父-子组件通讯、子-父组件通讯和同级组件之间的通讯。
1.父-子组件通讯
2.子-父组件通讯
3.同级组件之间的通讯
1.父-子组件通讯
1.1通讯的手腕
这是最常见的通讯体式格局,父组件只须要将子组件须要的props传给子组件,子组件直接经由过程this.props来运用。
1.2 通讯内容
更多要提的是怎样合理的设置子组件的props,要想将子组件设想成一个复用性强的通用组件,须要将能够复用的部份笼统出来,
笼统出来的props有两种构成,一种是简朴的变量,另一种是笼统出来处置惩罚某种逻辑的函数。
以Header 组件为例
笼统出来三个props,分别是中心的title,衬着组件左侧的renderLeftComponent,衬着组件右侧的renderRightComponent
Header的 部份完成
renderLeftComponent () {
let leftDOM = {};
if(this.props.renderLeftComponent) {
return this.props.renderLeftComponent();
}
if (this.props.showBack) {
let backFunc = this.props.onBack || this.goBack;
leftDOM = (<a onClick={backFunc.bind(this)}><i className="icon left-icon icon-left-arrow"></i></a>);
}
return leftDOM;
}
renderRightComponent () {
if(this.props.renderRightComponent) {
return this.props.renderRightComponent();
}
}
render () {
return (
<header className="header-wrapper">
<div className="header header-normal">
{this.renderLeftComponent()}
<span>{this.props.title || '维C果蔬'}</span>
{this.renderRightComponent()}
</div>
</header>
);
}
1.3 通讯的效果
1.1中Header组件 props的通讯效果 是子组件须要如许的属性来完成本身的展现。另有一种效果能够统称向子组件通报监听事宜,
前一种是子组件的需求,后一种更多的是父组件的需求,比方Listview的onEndReached这类属性,触起源是在子组件中,当子组件
的事宜被触发或许到达某种状况的时刻,挪用父组件从属性中传过来的要领。
2.子-父组件通讯
2.1 通讯的手腕
父-子组件通讯的手腕是经由过程子组件的props是子组件用父组件的东西,子-父组件通讯,是父组件用子组件的东西,应当将通报的内容直接写在子组件上,然后给子组件设置ref,父组件直接经由过程ref操纵子组件的属性。
2.2 通讯的内容
子组件的属性
2.3 通讯的效果
父组件想要挪用子组件的属性
3.同级组件之间的通讯
同级组件之间的通讯,是构建庞杂界面的粘合剂,哎呦喂,我好会比方啊
以维C果蔬的首页为例:
通讯1: Listview须要offsetHeight属性,Listview
Height的盘算公式:window.innerHeight-Banner的Height-Menu的Height,
而Banner和Menu的Height都是须要在其Mount的时刻才盘算。
通讯2: ListView须要Menu的MenuId,才够依据MenuId猎取sku数据。
3.1通讯的体式格局
同级组件之间的通讯照样须要经由过程父组件作为中介,应用屡次父-子组件通讯,项目中将须要通报的数据放在了父组件的state中,更改时能够自动的同步通报。
将 bannerHeight,menuHeight,MenuId放在state中。
父组件代码表示:
this.state {
bannerHeight: 0,
menuHeight: 0,
MenuId: 0
}
setBannerHeight(height) {
this.setState({bannerHeight:height});
}
setMenuHeight(height) {
this.setState({menuHeight:height});
}
onMenuClick(menuId) {
this.setState({menuId:menuId});
}
<Banner setBannerHeight={this.setBannerHeight.bind(this)} />
<Menu setMenuHeight={the.setMenuHeight.bind(this)} onMenuClick={this.onMenuClick.bind(this)} />
<SkuList offsetHeight={this.state.bannerHeight + this.state.menuHeight} menuId={this.state.menuId} />
3.2通讯的效果
当组件须要的props,不能直接从父组件中猎取时,须要父组件作为中介,再与其他的组件举行通讯猎取。