React Native中如何设置scrollTo()的速度?

13

我在按钮点击时使用以下代码来滚动页面:

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

滚动条运作正常,但是我想要减慢滚动的速度。我们该怎么做?


1
我认为这个开放的PR会对你有所帮助 https://github.com/facebook/react-native/pull/17422 - Nisarg Thakkar
2个回答

2

这是一个非常巧妙的解决方案,它使用了scrollview的内容高度来滚动整个视图(在挂载时)。然而,同样的技巧也可用于创建一个可以在任何给定时刻(到任何给定值)通过某些事件触发的滚动函数(通过添加监听器到动画值实现)。


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


0
在安卓上,您可以使用smoothScrollTo选项。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接