有時候我們需要直接改動組件并觸發(fā)局部的刷新,但不使用state
或是props
瞬浓。 setNativeProps
方法可以理解為web的直接修改dom初婆。使用該方法修改 View
、 Text
等 RN自帶的組件 猿棉,則不會觸發(fā)組件的 componentWillReceiveProps
磅叛、 shouldComponentUpdate
、componentWillUpdate
等組件生命周期中的方法萨赁。
使用例子
class MyButton extends React.Component({
setNativeProps(nativeProps) {
this._root.setNativeProps({ //這里輸入你要修改的組件style
height:48,
backgroundColor:'red'
});
},
render() {
return (
<View ref={component => this._root = component} {...this.props} style={styles.button}>
<Text>{this.props.label}</Text>
</View>
)
},
});
避免和render方法的沖突
如果要更新一個由render方法來維護的屬性宪躯,則可能會碰到一些出人意料的bug。因為每一次組件重新渲染都可能引起屬性變化位迂,這樣一來访雪,之前通過setNativeProps所設(shè)定的值就被完全忽略和覆蓋掉了详瑞。