2017-09-27 32 views
0

我正在嘗試更新按鈕按下時的視圖的backgroundColor。如果顏色是紅色的,我希望它變成橙色,反之亦然。如何檢查React Native中的視圖狀態?

我目前有按鈕將視圖從紅色更改爲橙​​色,但不是相反。

constructor(props) { 
    super(props); 
    this.state = { 
     viewColour: "red", 
    } 
} 

render() { 
    return (
     <View style={styles.parentView}> 
      <Button 
       title="Press here" 
       onPress={() => this.setState({viewColour:"orange"})} 
      /> 

      <View style={Object.assign({}, styles.colourSquare, {backgroundColor: this.state.viewColour})}/> 
     </View> 
    ); 
} 

我如何檢查什麼鑑於當前的顏色,以便確定什麼顏色,將其更改按下按鈕時?

回答

0

你應該做的

render() { 
return (
    <View style={styles.parentView}> 
     <Button 
      title="Press here" 
      onPress={() => this.setState({viewColour: this.state.viewColour == 'red' ? "orange" : 'red'})} 
     /> 

     <View style={[styles.colourSquare, {backgroundColor: this.state.viewColour}]}/> 
    </View> 
); 
} 
0

雖然穆罕默德的方法是有效的Facebook目前建議傳遞一個函數,而不是對setState對象時,新的狀態取決於舊狀態(according to the docs)。因此你應該做this.setState((prevState) => ({viewColour: prevState.viewColour == 'red' ? "orange" : 'red'}))

相關問題