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


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

首先创建一个 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 表示在计数停止时要做什么。

输出

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

更新于:2021 年 9 月 28 日

841 次浏览

开启你的职业生涯

完成课程获取认证

开始
广告
© . All rights reserved.