使用 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.