使用新的“Pressable”组件实现平滑过渡?

ido*_*ize 4 animation react-native expo react-native-reanimated-v2

我一直TouchableOpacity在我的 React Native 项目中使用它,以方便使用,但我有兴趣尝试新Pressable组件 - 考虑到它的 API 非常灵活。

然而,虽然新的PressableAPI 使我能够轻松地更改style基于pressed状态的道具等内容,但没有像TouchableOpacity!中的不透明度那样平滑/动画过渡。相反,按下/松开时会立即发生转换。

最好的使用方法是什么Pressable,同时又能在按下/未按下的样式更改之间实现良好、平滑的过渡?我想我必须以Animated某种方式使用 API?有人有这方面的例子吗?

小智 9

您可以使用 Animated Api 以下是 Animated Api 的示例:

import { Pressable, Animated, View } from "react-native";

const Component = () => {
  const animated = new Animated.Value(1);

  const fadeIn = () => {
    Animated.timing(animated, {
      toValue: 0.4,
      duration: 100,
      useNativeDriver: true,
    }).start();
  };
  const fadeOut = () => {
    Animated.timing(animated, {
      toValue: 1,
      duration: 200,
      useNativeDriver: true,
    }).start();
  };

  return (
    <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
      <Pressable onPressIn={fadeIn} onPressOut={fadeOut}>
        <Animated.View
          style={{
            opacity: animated,
            backgroundColor: "red",
            padding: 50,
            borderRadius: 20,
          }}
        >
          <Text>Text</Text>
        </Animated.View>
      </Pressable>
    </View>
  );
};
Run Code Online (Sandbox Code Playgroud)

动画 Api 文档: https ://reactnative.dev/docs/animated

我还建议查看重生库来创建具有本机性能的动画

https://docs.swmansion.com/react-native-reanimated/