組件化是react-native的最大優點之一,因為組件化我們可以做到局部重新整理,提高效能。
如圖所示 父組件包含連個子組件 添加可以動態增加子組件
log輸出:
add關鍵代碼:
_onPress() { if(show){/*顯示刪除時 不能添加*/ return ; } let arr = this.state.list; arr.push(this._renderItem()); this.setState({ list: arr, }); }; _renderItem() { count = this.id+1; this.id = count; return (<CeilItem ref={(component)=>{ this.reflist.push(component) }} id={count} onChildHanlder={this.onChildHanlder} > </CeilItem> ); }
點擊show動態更新子組件 但不重新整理父組件
如下所示:
log:
只重新整理了子view 沒有重新整理父view
show關鍵代碼:
父組件:
/*改變item布局*/ _show(){ show = show?false:true; for(let i=0;i<this.reflist.length;i++){ this.reflist[i].change(show); } } onChildHanlder(inputId){ let len = this.reflist.length; for(let i=0;i<len;i++){ let id=this.reflist[i].props.id; if(inputId==id){ del++; console.log("delete i: ",i); this.reflist[i].delete(); } } /*全部刪除後才可以添加*/ show = del==count?false:show; }
子組件代碼:
change(flag){ this.setState({flag:flag}); } delete(){ this.setState({delete:true}); } hide(){ let centerPart_right = 0; let rightPart_width = 0; return (<View style={styles.Item}> <View style={styles.leftPart}> </View> <View style={[styles.centerPart, {marginRight:centerPart_right}]}> </View> <View style={[styles.rightPart,{width:rightPart_width,position:'absolute', right:0}]}> </View> </View>); } show(){ let id=this.props.id; let onChildHanlder=this.props.onChildHanlder; let centerPart_right = 70; let rightPart_width = 60; return (<View style={styles.Item}> <View style={styles.leftPart}> </View> <View style={[styles.centerPart, {marginRight:centerPart_right}]}> </View> <View style={[styles.rightPart,{width:rightPart_width,position:'absolute', right:0},{justifyContent:'center', alignItems:'center'}]}> <TouchableOpacity onPress={()=>{onChildHanlder(id)}}> <Text style={[styles.textStyle]}> del </Text> </TouchableOpacity> </View> </View>); }
github完整代碼: https://github.com/wuyunqiang/react-/tree/master/test/view