2017-02-10 208 views
1

我希望在按下按鈕時更改其顏色。我嘗試檢查出其他類似的主題,但我找不到解決方案。代碼呈現並且初始按鈕顏色爲紅色,但是當我按下它時,沒有任何反應。通過在React Native上使用onPress更改按鈕顏色

export default class someProgram extends Component { 
    render() { 

    var buttonColor = "red"; 

    function changeButtonColor(){ 
    if(this.buttonColor === "red"){ 
     this.buttonColor = "green"; 
    } 
    else{ 
     this.buttonColor = "red"; 
    } 
    } 

    return (
    <View style={styles.container}>  
     <Button 
     title="Press me!" 
     color={buttonColor} 
     onPress={() => {changeButtonColor(buttonColor)}} 
     /> 
    </View> 
); 
} 
} 

回答

2

您應該跟蹤組件狀態中的顏色。作爲一方,請務必瞭解關鍵字這個的真正含義。做一個console.log(this)並親自查看。 (1)在構造函數中設置初始狀態;(2)在構造函數中設置初始狀態;(3)在構造函數中設置初始狀態;

(2)訪問使用this.state.someProp

然後(3)調整後使用this.setState({ someProp: someValue })的狀態的狀態值。

1)初始狀態

constructor(props) { 
    super(props); 

    this.state = { 
    buttonColor: 'red'; // default button color goes here 
    }; 
} 

2)訪問設置新狀態的狀態& 3)

onButtonPress =() => { 
    this.setState({ buttonColor: 'someNewColor' }); 
} 

render() { 
    // ... 
    return (
    {/* ... */} 
    <Button 
     color={this.state.buttonColor} 
     onPress={onButtonPress} 
    /> 
) 

注意的代碼的某些部分已被略去把重點放在問題在手。

+0

太棒了。完美工作。非常感謝你。 – user3348949