0

我一直TouchableOpacity在我的 react native 项目中使用它以方便使用,但我有兴趣尝试使用新Pressable组件——考虑到它的 API 有多灵活。

然而,虽然新的API 让我能够轻松地根据状态Pressable更改诸如道具之类的东西,但没有像! 相反,当按下/松开时,转换会立即发生。stylepressedTouchableOpacity

什么是最好的使用方式,Pressable而且在按下/未按下的样式更改之间做出漂亮、平滑的过渡?我假设我必须以Animated某种方式使用 API?有没有人有这方面的例子?

4

1 回答 1

1

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

import React from "react";
import { Pressable, Animated } 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>
  );
};

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

我还建议查看 reanimated 库以创建具有本机性能的动画

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

于 2021-11-03T17:54:50.633 回答