我一直在使用Scrollview它包含一个包含页面指示器作为数字的列表视图。当我点击它们时,我希望它们滚动以使所选数字位于中心
喜欢
4 5 6 [7] 8 9
7是这里选择的数字,当我在这里点击9时
滚动视图向左滚动,以便视图显示为
7 8 [9] 10 11
我正在使用scrollTo(x : calculated , y : 0 , animated : true)
但是滚动太慢了。我希望滚动速度很快或可以通过参数控制,我已经尝试了持续时间,scrollTo但这不起作用。
我一直在使用Scrollview它包含一个包含页面指示器作为数字的列表视图。当我点击它们时,我希望它们滚动以使所选数字位于中心
喜欢
4 5 6 [7] 8 9
7是这里选择的数字,当我在这里点击9时
滚动视图向左滚动,以便视图显示为
7 8 [9] 10 11
我正在使用scrollTo(x : calculated , y : 0 , animated : true)
但是滚动太慢了。我希望滚动速度很快或可以通过参数控制,我已经尝试了持续时间,scrollTo但这不起作用。
这是目前不可能的。调用 scrollTo 导致调用scrollResponderScrollTo,然后调用ios 实现或android 实现。这将是人们必须实现滚动速度的地方。
这是一个非常简洁的解决方案,它使用滚动视图的内容高度来滚动整个视图(安装时)。但是,可以使用相同的技巧(将侦听器添加到动画值)来创建滚动函数,该函数可以在任何给定时刻(到任何给定值)由某个事件触发。
import { useEffect, useRef, useState } from 'react'
import { Animated, Easing, ScrollView } from 'react-native'
const SlowAutoScroller = ({ children }) => {
const scrollRef = useRef()
const scrollAnimation = useRef(new Animated.Value(0))
const [contentHeight, setContentHeight] = useState(0)
useEffect(() => {
scrollAnimation.current.addListener((animation) => {
scrollRef.current &&
scrollRef.current.scrollTo({
y: animation.value,
animated: false,
})
})
if (contentHeight) {
Animated.timing(scrollAnimation.current, {
toValue: contentHeight,
duration: contentHeight * 100,
useNativeDriver: true,
easing: Easing.linear,
}).start()
}
return () => scrollAnimation.current.removeAllListeners()
}, [contentHeight])
return (
<Animated.ScrollView
ref={scrollRef}
onContentSizeChange={(width, height) => {
setContentHeight(height)
}}
onScrollBeginDrag={() => scrollAnimation.current.stopAnimation()}
>
{children}
</Animated.ScrollView>
)
}