如何制作在 React-Native React Navigation 5 中向下滚动时从透明颜色变为不透明颜色的动画标题?

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

我正在尝试使标题在 React-Native React Navigation 5 中使用时从透明动画到纯色不透明颜色。

滚动到一半时开始转变为不透明


达到最大偏移量时变得完全不透明

reactjs react-native react-navigation react-navigation-v5
3个回答
13
投票

您可以通过将标题样式不透明度设置为动画值来做到这一点。

首先定义您的动画值,我们将插入 yOffset 以获得所需的不透明度。

const yOffset = useRef(new Animated.Value(0)).current;
const headerOpacity = yOffset.interpolate({
  inputRange: [0, 200],
  outputRange: [0, 1],
  extrapolate: "clamp",
});

然后你想将animated.event监听器附加到动画滚动视图

<Animated.ScrollView
  onScroll={Animated.event(
    [
      {
        nativeEvent: {
          contentOffset: {
            y: yOffset,
          },
        },
      },
    ],
    { useNativeDriver: true }
  )}
  scrollEventThrottle={16}
>

您的内容应该位于滚动视图内

在屏幕中添加安装或使用效果,将animatedValue 设置为标题不透明度

useEffect(() => {
  navigation.setOptions({
    headerStyle: {
      opacity: headerOpacity,
    },
    headerBackground: () => (
      <Animated.View
        style={{
          backgroundColor: "white",
          ...StyleSheet.absoluteFillObject,
          opacity: headerOpacity,
        }}
      />
    ),
    headerTransparent: true,
  });
}, [headerOpacity, navigation]);

我使用了标题透明和标题背景,以便背景组件也发生变化。

这是一个例子:

https://snack.expo.io/@dannyhw/react-navigation-animated-header


0
投票
const handleScroll = () => {
  YourElementRef.current.style.backgroundColor = `rgba(245, 245, 245, ${window.scrollY > 300 ? 1 : '0.' + (window.scrollY * 3)})`;
}
window.addEventListener('scroll', handleScroll, true);

您需要添加滚动侦听器并调用为其设置动画的函数。 滚动元素由 ref stuff 表示。例如

const YourElementRef = React.useRef(null);
<SomeElement ref={YourElementRef}...

0
投票

我按照Danny的回答成功实现了标题动画。

我想分享我的实现动画的解决方案标题标题

  1. 将 Animated.Header 包裹在 Text 组件周围,文本将成为标题标题):

    useEffect(() => { 导航.setOptions({ 标题: ””, 标题样式:{ 不透明度:标题不透明度, }, 标题背景:() => ( 这是标题 ), 标题透明:true, }); }, [标题不透明度,导航]);

  2. 使用这些样式来模仿原生 iOS 标题样式:

    const 样式 = StyleSheet.create({ 标题标题:{ 字体大小:17, 字体粗细:“600”, 底部:12, 文本对齐:“居中”, 弹性:1, 位置:“绝对”, 宽度:“100%”, }, ... })

© www.soinside.com 2019 - 2024. All rights reserved.