如何在reanimated 2中使用diffClamp?

问题描述 投票:0回答:2

我正在尝试根据重新动画 2 的滚动事件隐藏和显示标题useAnimatedScrollHandler并且我需要使用diffClamp所以每当用户向上滚动时标题应该显示在比整个滚动事件更短的时间 contentOffset.y 值,但问题是 diffClamp 是我认为来自 reanimated v1 的,我需要使用 useAnimatedStyle 钩子以便在 reanimated v2 中对样式进行动画处理,最后它给出了错误。

有人可以帮忙吗?

react-native react-native-reanimated react-native-reanimated-v2
2个回答
5
投票
const clamp = (value, lowerBound, upperBound) => {
    "worklet";
    return Math.min(Math.max(lowerBound, value), upperBound);
};

const scrollClamp = useSharedValue(0);

const scrollHandler = useAnimatedScrollHandler({
    onScroll: (event, ctx) => {

        const diff = event.contentOffset.y - ctx.prevY;

        scrollClamp.value = clamp(scrollClamp.value + diff, 0, 200);

    },
    onBeginDrag: (event, ctx) => {
        ctx.prevY = event.contentOffset.y;
    }
});

const RStyle = useAnimatedStyle(() => {

    const interpolateY = interpolate(
        scrollClamp.value,
        [0, 200],
        [0, -200],
        Extrapolate.CLAMP
    )

    return {
        transform: [
            { translateY: interpolateY }
        ]
    }
})

0
投票

对于带有 diffclamp 的标题动画,请使用。 👇

  const animatedValue = useSharedValue(0);
  const backupValue = useSharedValue(0);
  const MAX_HEIGHT = 200;

  const scrollHandler = useAnimatedScrollHandler({
    onScroll: (event) => {
      const newValue =
        animatedValue.value + event.contentOffset.y - backupValue.value;

      animatedValue.value = Math.min(Math.max(newValue, 0), MAX_HEIGHT);
      backupValue.value = Math.max(0, event.contentOffset.y);
    },
  });

  const animatedHeaderStyle = useAnimatedStyle(() => {
    return {
      transform: [
        {
          translateY: interpolate(
            animatedValue.value,
            [0, MAX_HEIGHT],
            [0, -MAX_HEIGHT],
            Extrapolation.CLAMP
          ),
        },
      ],
    };
  });
© www.soinside.com 2019 - 2024. All rights reserved.