【问题标题】:Change a button color by using onPress on React Native在 React Native 上使用 onPress 更改按钮颜色
【发布时间】:2017-06-29 03:48:11
【问题描述】:

我想让按钮在按下时改变它的颜色。我尝试查看其他类似主题,但找不到解决方案。代码呈现,初始按钮颜色为红色,但当我按下它时,什么也没有发生。

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

【问题讨论】:

    标签: android button colors react-native


    【解决方案1】:

    您应该跟踪组件状态中的颜色。另一方面,请务必了解关键字 this 的真正含义。做一个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) 访问状态 & 3) 设置新状态

    onButtonPress = () => {
      this.setState({ buttonColor: 'someNewColor' }); 
    }
    
    render() {
      // ...
      return (
        {/* ... */}
        <Button
          color={this.state.buttonColor}
          onPress={onButtonPress}
        />
      )
    

    请注意,为了专注于手头的问题,省略了部分代码。

    【讨论】:

    • 太棒了。工作完美。非常感谢。
    猜你喜欢
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 2021-05-23
    • 2023-01-28
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    相关资源
    最近更新 更多