有時候我們需要直接改動組件并觸發局部的刷新,但不使用state
或是props
。 setNativeProps
方法可以理解為web的直接修改dom。使用該方法修改 View
、 Text
等 RN自帶的組件 ,則不會觸發組件的 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所設定的值就被完全忽略和覆蓋掉了。