繁体   English   中英

使用TouchableHighlight在React Native中按下时如何更改按钮颜色?

[英]How to change button color when pressed in React Native using TouchableHighlight?

我目前正在开发一个应用程序,但在弄清楚如何使用TouchableHighlight按下按钮以更改颜色后,我遇到了麻烦。 不要与underlayColor道具混淆,我知道它是TouchableHighlight的一部分,它仅在按下按钮时更改颜色,然后返回其常规颜色。

这就是我到目前为止(为了简单起见,一些代码已被省略):

import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TouchableHighlight,
Alert,
} from 'react-native';


class MeetingScreen extends Component {
  constructor(props){
       super(props);
       this.state = {
        buttonColor: '#7395AE',
        }
this.onButtonPress=this.onButtonPress.bind(this);

  }

onButtonPress(){
  this.setState({ buttonColor: 'red' });
}

    render() {
  return (
    <View style={styles.container}>
      <TouchableHighlight
        style={styles.talk}
        color={this.state.buttonColor}
        onPress={() => this.state.buttonColor}
        selected={this.onButtonPress}
      >
        <View>
          <Text style={styles.welcome} >
            Talk
          </Text>
        </View>
      </TouchableHighlight>
    </View>
  );
}
};


const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#7395AE',
  },
  welcome: {
    fontSize: 30,
    textAlign: 'center',
    margin: 10,
    color: '#ffffff',
  },
  talk:{
    height: 200,
    width: 200,
    borderWidth: 5,
    backgroundColor: '#7395AE',
    borderRadius: 100,
    borderColor: '#557A95',
    justifyContent:'center',
    alignItems:'center',
    borderRadius: 100
  },
});

export default connect(mapStoreToProps, mapDispatchToProps)(MeetingScreen);

我在StackOverflow上查看了其他答案,并尝试了其中的很大一部分,但找不到适合我问题的任何答案。 我也查看了React Native文档,但找不到任何有用的东西。 现在的代码只是显示按钮,按下该按钮时它会变成黑色,但是按下后会恢复为原始颜色。 我要寻找的是使按钮变为红色并在被按下后保持红色。 任何帮助将不胜感激。 非常感谢您提前提供的帮助!

<TouchableHighlight
  style={[styles.talk, { backgroundColor: this.state.buttonColor}]} //Or if don't want "backgroundColor:" and just need change the text color use => "color:""
  onPress={() => this.state.buttonColor}
  selected={this.onButtonPress}/>
onPress={() => this.state.buttonColor}
selected={this.onButtonPress}

这似乎是错误的,onPress应该调用您的onButtonPress函数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM