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

新手上路,请多包涵

我希望我的应用程序中的按钮样式在按下时发生变化。做这个的最好方式是什么?

原文由 domi91c 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 609
2 个回答

使用 TouchableHighlight

这里有一个例子:

在此处输入图像描述

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

export default function Button() {

  var [ isPress, setIsPress ] = React.useState(false);

  var touchProps = {
    activeOpacity: 1,
    underlayColor: 'blue',                               // <-- "backgroundColor" will be always overwritten by "underlayColor"
    style: isPress ? styles.btnPress : styles.btnNormal, // <-- but you can still apply other style changes
    onHideUnderlay: () => setIsPress(false),
    onShowUnderlay: () => setIsPress(true),
    onPress: () => console.log('HELLO'),                 // <-- "onPress" is apparently required
  };

  return (
    <View style={styles.container}>
      <TouchableHighlight {...touchProps}>
        <Text>Click here</Text>
      </TouchableHighlight>
    </View>
  );
}

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  btnNormal: {
    borderColor: 'blue',
    borderWidth: 1,
    borderRadius: 10,
    height: 30,
    width: 100,
  },
  btnPress: {
    borderColor: 'blue',
    borderWidth: 1,
    height: 30,
    width: 100,
  }
});

原文由 Besart Hoxhaj 发布,翻译遵循 CC BY-SA 4.0 许可协议

React Native 现在提供了一个新的 Pressable 组件,可以检测不同阶段的压力交互。因此,要更改组件的颜色(通常是任何样式),请参考以下示例:

 <Pressable
  style={({ pressed }) => [{ backgroundColor: pressed ? 'black' : 'white' }, styles.btn ]}>
  {({ pressed }) => (
    <Text style={[{ color: pressed ? 'white' : 'black' }, styles.btnText]}>
      {text}
    </Text>
  )}
</Pressable>

代码分解:

 style={({ pressed }) => [{ backgroundColor: pressed ? 'black' : 'white' }, styles.btn ]}

这里 style 道具接收 pressed(boolean) 反映 Pressable 是否被按下并返回一个样式数组。

 {({ pressed }) => (
    <Text style={[{ color: pressed ? 'white' : 'black' }, styles.btnText]}>
      {text}
    </Text>
)}

这里的文本样式也可以修改为 pressed 也可供 Pressable 组件的子级访问。

原文由 Ankush Chauhan 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题