【问题标题】:Animating scrollTop using react-spring使用 react-spring 动画 scrollTop
【发布时间】:2020-07-10 22:14:22
【问题描述】:

这应该很简单,但我认为我遗漏了一些关于 Spring 工作原理的关键信息,文档没有多大帮助。

我有一个动态列表,用户可以添加元素,当这种情况发生时,我想使用 React Spring 动画滚动到页面底部(由currentBottomY 变量标识)

我有这样的事情

const mainRef = useRef<HTMLElement | null>(null)

const [y, setY] = useSpring({
    from: { y: mainRef?.current?.scrollTop || 0 },
    onFrame: props => {
       mainRef.current.scrollTop = props.y
    },
})

const onAddRow = () => {
    setY({ y: currentBottomY })
}

return (
    <animated.div ref={mainRef}>
        <List />
    </animated.div>
)

我收到错误消息,说我无法在其中定义 fromonFrame,但在文档中另有说明,我真的无法对此做出正面或反面,有什么帮助吗?

【问题讨论】:

    标签: javascript reactjs react-spring


    【解决方案1】:

    如果您想在以后的调用中控制更新,(这似乎是您所做的),请尝试传递给 useSpring 挂钩函数。

    const [y, setY] = useSpring(() => ({
      from: { y: mainRef?.current?.scrollTop || 0 },
      onFrame: props => {
         mainRef.current.scrollTop = props.y
      },
    }));
    

    【讨论】:

    • 感谢这帮助我深入了解它
    • 你会如何使用 react-spring v9 做到这一点?
    • @rssfrncs 用于版本 9.x.x 而不是 onFrame 使用 onChange 而不是道具,您需要解构对象 { value: { y } } 在这种情况下是 y 但如果您设置其他变量则更改跨度>
    【解决方案2】:

    感谢 Matt 的指点,我解决了这个问题并创建了一个可重用的钩子,它接受容器的 ref 并在调用 scrollToBottom() 函数时滚动到底部。

    import { useSpring } from 'react-spring'
    
    const useScrollAnimation = (
      containerRef: React.MutableRefObject<HTMLDivElement | null>
    ): { animate: () => void } => {
      const [, setY] = useSpring(() => ({
        y: 0,
        onFrame: (props: any) => {
          props
        },
      }))
    
      const scrollToBottom = () => {
        setTimeout(() => {
          const current = containerRef?.current
          if (current) {
            const { scrollHeight } = current
            setY({
              config: { duration: 200 },
              y: scrollHeight - current.getBoundingClientRect().bottom,
              onFrame: (props: any) => (current.scrollTop = props.y),
            })
          }
        }, 0)
      }
    
      return { scrollToBottom }
    }
    
    export default useScrollAnimation
    

    【讨论】:

    • 你会如何使用 react-spring v9 做到这一点?
    猜你喜欢
    • 2013-05-04
    • 1970-01-01
    • 2018-02-14
    • 2020-10-07
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多