gpt4 book ai didi

react-native - 我们如何在 React Native 中为 scrollTo() 设置速度?

转载 作者:行者123 更新时间:2023-12-04 02:33:16 29 4
gpt4 key购买 nike

我使用以下按钮单击按钮滚动页面:

this.scrollTo({y: height, x: 0, animated: true})

滚动工作正常,但是我想减慢滚动动画的速度。
我们怎么做?

最佳答案

这是一个非常简洁的解决方案,它使用 ScrollView 的内容高度来滚动整个 View (安装时)。但是,可以使用相同的技巧(将监听器添加到动画值)来创建滚动函数,该函数可以在任何给定时刻(到任何给定值)由某个事件触发。


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>
)
}

关于react-native - 我们如何在 React Native 中为 scrollTo() 设置速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44820599/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com