【问题标题】:Smooth transitions with the new "Pressable" component?使用新的“Pressable”组件实现平滑过渡?
【发布时间】:2021-12-18 00:33:46
【问题描述】:

我一直在使用 TouchableOpacity 以便在我的 react native 项目中使用,但我有兴趣尝试新的 Pressable 组件,因为它的 API 非常灵活。

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

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

【问题讨论】:

标签: react-native animation expo react-native-reanimated-v2


【解决方案1】:

您可以使用动画 API 下面是一个动画 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/

【讨论】:

    猜你喜欢
    • 2016-10-07
    • 2020-09-17
    • 2021-11-01
    • 2012-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多