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

标签 react-native scrollto

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

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/

相关文章:

android - 崩溃后的 react native 应用程序显示闪屏

javascript - 错误无法读取未定义的属性(读取 'configurations')。类型错误 : Cannot read properties of undefined (reading 'configurations' )

javascript - 由于 header 导致 scrollto 偏移 javascript 的问题

javascript - 由于 header 导致 scrollto 偏移 javascript 的问题

android - React Native PanResponder 限制X位置

javascript - 使用状态时在 React Native 中出现 undefined object 错误?

android - React-Native:检查字符串是否包含字符串

javascript - anchor 的外部链接 - 可以延迟滚动吗?

安卓 ScrollView : Automatically scroll to a few pixels (dips) above a certain view

javascript - 移动到最后一里时回到第一里(使用 Jquery 滚动到下一个)