2016-08-25 7 views
1

Touchable 요소를 감싸고 Replay Native 구성 요소를 만들고 테마 색상을 소품으로 사용합니다. 테마에 따라 단추 배경색이 달라집니다. 지금 나는 소품을 검사하고 그에 따라 스타일을 선택하는 렌더링 함수에 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

관련 문제