如何制作 Header 在 React-Native React Navigation 5 中向下滚动时从透明变为不透明颜色的动画?
How to make a Header that Animates from Transparent to Opaque Color on Scrolling down in React-Native React Navigation 5?
我正在尝试制作 header,在使用 React-Native React Navigation 5.
向下滚动时,它会从透明变为纯不透明。
滚动到一半时开始过渡到不透明
达到最大偏移量时变得完全不透明
const handleScroll = () => {
YourElementRef.current.style.backgroundColor = `rgba(245, 245, 245, ${window.scrollY > 300 ? 1 : '0.' + (window.scrollY * 3)})`;
}
window.addEventListener('scroll', handleScroll, true);
您需要添加滚动侦听器并调用为其设置动画的函数。
滚动元素由 ref 东西表示。例如
const YourElementRef = React.useRef(null);
<SomeElement ref={YourElementRef}...
您可以通过将 header 样式不透明度设置为动画值来实现。
首先定义您的动画值,我们将插入 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}
>
您的内容应该在滚动视图中
在您的屏幕上添加一个安装或使用效果,您将动画值设置为 header 不透明度
useEffect(() => {
navigation.setOptions({
headerStyle: {
opacity: headerOpacity,
},
headerBackground: () => (
<Animated.View
style={{
backgroundColor: "white",
...StyleSheet.absoluteFillObject,
opacity: headerOpacity,
}}
/>
),
headerTransparent: true,
});
}, [headerOpacity, navigation]);
我使用了 header 透明和 header 背景,这样背景组件也会发生变化。
这是一个例子:
https://snack.expo.io/@dannyhw/react-navigation-animated-header
我正在尝试制作 header,在使用 React-Native React Navigation 5.
向下滚动时,它会从透明变为纯不透明。滚动到一半时开始过渡到不透明
达到最大偏移量时变得完全不透明
const handleScroll = () => {
YourElementRef.current.style.backgroundColor = `rgba(245, 245, 245, ${window.scrollY > 300 ? 1 : '0.' + (window.scrollY * 3)})`;
}
window.addEventListener('scroll', handleScroll, true);
您需要添加滚动侦听器并调用为其设置动画的函数。 滚动元素由 ref 东西表示。例如
const YourElementRef = React.useRef(null);
<SomeElement ref={YourElementRef}...
您可以通过将 header 样式不透明度设置为动画值来实现。
首先定义您的动画值,我们将插入 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}
>
您的内容应该在滚动视图中
在您的屏幕上添加一个安装或使用效果,您将动画值设置为 header 不透明度
useEffect(() => {
navigation.setOptions({
headerStyle: {
opacity: headerOpacity,
},
headerBackground: () => (
<Animated.View
style={{
backgroundColor: "white",
...StyleSheet.absoluteFillObject,
opacity: headerOpacity,
}}
/>
),
headerTransparent: true,
});
}, [headerOpacity, navigation]);
我使用了 header 透明和 header 背景,这样背景组件也会发生变化。
这是一个例子:
https://snack.expo.io/@dannyhw/react-navigation-animated-header