2016-08-25 111 views
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语句移到其他地方吗?有没有另一种方法呢?

回答

1
Rather than doing this what about : 

super(props); 
this.state = {bgColor : (this.props.theme === 'blue')? styles.blueBg : styles.redBg}; 

render(){ 
return (
<TouchableHighlight style={[styles.button,this.state.bgColor]}> 
    {/* ... */} 
    </TouchableHighlight> 

) 
} 
+0

好吧,在初始化时设置主题似乎是合理的,因为渲染可能会被调用很多次。但是会有更多的主题,所以我不会使用三元运算符。 – nbkhope