在React Native上使用onPress更改按钮颜色

时间:2017-02-10 17:36:28

标签: android button colors react-native

我希望按下按钮可以改变颜色。我尝试检查其他类似的主题,但我找不到解决方案。代码呈现并且初始按钮颜色为红色,但是当我按下它时,没有任何反应。

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>
  );
 }
}

1 个答案:

答案 0 :(得分:3)

您应该跟踪组件状态中的颜色。作为一方,请务必了解关键字的真正含义。做一个console.log(this)并亲自看看。

无论如何,你可以

(1)在构造函数中设置初始状态;

(2)使用this.state.someProp

从州获取值

然后(3)稍后使用this.setState({ someProp: someValue })调整状态。

1)初始状态

constructor(props) {
  super(props);

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

2)访问State&amp; 3)设置新状态

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

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

请注意,代码的某些部分被忽略,以便专注于手头的问题。