1
我製作了一個React Native組件,它包裝了一個Touchable元素並將主題顏色作爲一個道具。不同的主題使按鈕背景顏色不同。現在我在渲染功能檢查道具,並選擇相應風格的if語句:在React Native中製作帶有動態背景色的按鈕
render() {
var bgColor;
if (this.props.theme === 'blue') {
bgColor = styles.blueBg;
}
else if (this.props.theme === 'red') {
bgColor = styles.redBg;
}
// (...)
return (
<TouchableHighlight style={[styles.button, bgColor]}>
{/* ... */}
</TouchableHighlight>
);
}
const styles = StyleSheet.create({
// ...
blueBg: {
backgroundColor = 'blue'
},
redBg: {
backgroundColor = 'red'
},
});
這是這樣做的正確方法?我應該把我的if語句移到其他地方嗎?有沒有另一種方法呢?
好吧,在初始化時設置主題似乎是合理的,因爲渲染可能會被調用很多次。但是會有更多的主題,所以我不會使用三元運算符。 – nbkhope