使用 react-spring 在 React.js 中实现自动滚动动画

react jsjavascript libraryfront end technology更新于 2025/11/17 7:40:17

在本文中,我们将了解如何使用 react-spring 包在 React JS 中创建滚动到顶部的动画。

首先创建一个 React 项目 −

npx create-react-app tutorialpurpose

现在转到项目目录 −

cd tutorialpurpose

示例

安装 react-spring 包 −

npm install react-spring

react-spring 用于向我们的网站添加基于 Spring 概念的动画。

接下来,添加以下代码行在 App.js 中 −

import React,{useState} from 'react'
import { useSpring, animated } from 'react-spring'

export default function App(){
   const [flip, set] = useState(false)

   const words = ['We', 'came.', 'We', 'saw.', 'We', 'hold', 'it s', 'hands.']

   const { scroll } = useSpring({
      scroll: (words.length - 1) * 50,
      from: { scroll: 0 },
      reset: true,
      reverse: flip,
      delay: 200,
      onRest: () => set(!flip),
   })
   return (
      <animated.div
      style={{
         position: 'relative',
         width: '100%',
         height: 60,
         overflow: 'auto',
         fontSize: '1em',
         marginTop:200 ,
         border:"1px solid black"
      }}
      scrollTop={scroll}>
      {words.map((word, i) => (
         <div
            key={`${word}_${i}`}
            style={{ width: '100%', height: 50, textAlign: 'center' }}>
            {word}
         </div>
      ))}
      </animated.div>
   )
}

解释

在 spring 对象的 scroll 属性中,我们定义了滚动的幅度。如果将值从 50 更改为 20,则只会滚动三个单词。

from 属性指示从哪里开始滚动;"0"表示从哪里开始滚动。表示从头开始滚动。

我们还有一些额外的属性,例如

  • reset 用于循环

  • reverse 表示计数的开始或结束时间

  • delay 用于在动画之间引入时间延迟,以及

  • onRest 表示计数停止时执行的操作。

输出

执行后,将产生以下输出 −


相关文章


有用资源