在 React JS 中新增 Lottie 動畫


Lottie 是一種開源動畫檔案格式,它小巧、高質量、具有互動性,並且可以在執行時進行操作。讓我們學習如何在 React.js 中實現 Lottie 動畫。Lottie 動畫主要用於載入螢幕或作為啟動螢幕。它在我們的 React 專案中以 JSON 格式編寫和實現。

示例

前往官方 Lottie 動畫網站並下載 Lottie JSON。

我將使用的動畫連結 −

 https://lottiefiles.com/74546-character-02#/

將 JSON 檔案命名為 "myloader.json",並將其與 App.js. 位於同一級別。

現在安裝 react-lottie 包 −

npm i --save react-lottie

Lottie 庫將用於將 lottie 動畫的 JSON 檔案新增到你的 React 網站。

App.js 中新增以下程式碼行 −

import Lottie from "react-lottie";

// importing lottie animation JSON
// note that you can use any variable in place of "animation"
import animation from './myloader.json'
function App() {
   const defaultOptions = {
      loop: true,
      autoplay: true,
      // here is where we will declare lottie animation
      // "animation" is what we imported before animationData: animation,
      rendererSettings: {
         preserveAspectRatio: "xMidYMid slice",
      },
   };

   return (
      <div>
         <Lottie options={defaultOptions} height={300} width={300} />
      </div>
   );
}

export default App;

在 defaultOptions 中,我們簡單地添加了一些動畫屬性並連結到我們的 Lottie 動畫 JSON。然後我們用預設選項呈現一個 lottieView 並連結到動畫。

輸出

它將生成以下輸出 −

更新於: 28-Sep-2021

1K+ 瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告