小编典典

在React Native中按下时更改按钮样式

reactjs

我希望我的应用程序中的按钮样式在按下时可以更改。做这个的最好方式是什么?


阅读 575

收藏
2020-07-22

共1个答案

小编典典

使用TouchableHighlight

这里是一个例子:

在此处输入图片说明

'use strict';

 import React, {
Component,
StyleSheet,
PropTypes,
View,
Text,
TouchableHighlight
} from "react-native";

export default class Home extends Component {
constructor(props) {
    super(props);
    this.state = { pressStatus: false };
}
_onHideUnderlay() {
    this.setState({ pressStatus: false });
}
_onShowUnderlay() {
    this.setState({ pressStatus: true });
}
render() {
    return (
        <View style={styles.container}>
            <TouchableHighlight
                activeOpacity={1}
                style={
                    this.state.pressStatus
                        ? styles.buttonPress
                        : styles.button
                }
                onHideUnderlay={this._onHideUnderlay.bind(this)}
                onShowUnderlay={this._onShowUnderlay.bind(this)}
            >
                <Text
                    style={
                        this.state.pressStatus
                            ? styles.welcomePress
                            : styles.welcome
                    }
                >
                    {this.props.text}
                </Text>
            </TouchableHighlight>
        </View>
    );
}
}

Home.propTypes = {
text: PropTypes.string.isRequired
};

const styles = StyleSheet.create({
container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF"
},
welcome: {
    fontSize: 20,
    textAlign: "center",
    margin: 10,
    color: "#000066"
},
welcomePress: {
    fontSize: 20,
    textAlign: "center",
    margin: 10,
    color: "#ffffff"
},
button: {
    borderColor: "#000066",
    borderWidth: 1,
    borderRadius: 10
},
buttonPress: {
    borderColor: "#000066",
    backgroundColor: "#000066",
    borderWidth: 1,
    borderRadius: 10
}
});
2020-07-22