6

推荐!从零开发一套基于React的加载动画库

 1 year ago
source link: https://www.51cto.com/article/749926.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

推荐!从零开发一套基于React的加载动画库

作者:徐小夕 2023-03-22 23:23:25
从技术上, 为了让使用者使用的更轻量简单, 我将 loaders.css 的每个动画样式和元素拆成了一个个动画组件, 并设计了相对灵活的 api 接口, 使得开发者可以更简单高效的使用。

之前在项目开发中经常会遇到需要开发各种各样加载动画的需求, 我们可以使用已有的动画库手动改造实现(比如说基于 loaders.css 手动改造), 也可以自己独立设计, 但是这意味着需要花一定的时间调研和开发.

为了减少这部分的时间, 并让加载动画的设计更加简化和易用, 我开发了一款开箱即用的加载动画库 react-loading, 内置了多种风格的加载动画, 开发者可以轻松选择自己需要的动画, 并一键安装到自己的项目中, 简单又轻量.

图片

github地址: https://github.com/MrXujiang/react-loading

接下来就和大家一起介绍一下这个动画库.

@alex_xu/react-loading​ 是基于 loaders.css​ 二次封装的 React 加载动画组件库, 帮你轻松的在项目中使用不同风格的加载动画.

demo.gif

从技术上, 为了让使用者使用的更轻量简单, 我将 loaders.css​ 的每个动画样式和元素拆成了一个个动画组件, 并设计了相对灵活的 api 接口, 使得开发者可以更简单高效的使用, 如下:

图片

该动画组件库采用 React Hooks​ 和 Typescript​ 实现, 分为 Loader​ 容器 和 Spining .

Loader​ 容器主要是对加载动画做整体封装, 使得我们对 Spining​ 动画组件的使用更简单, Spining​ 主要提供动画 “骨架” . Loader 具体实现如下:

import React from 'react';
import { ILoadingProp } from '../type';
import './index.less';

const Loader: React.FC<ILoadingProp> = ({
  text,
  visible = true,
  textOffset,
  textColor,
  style,
  children,
}) => {
  return visible ? (
    <div className="react-loader-wrap" style={style}>
      {children}
      {!!text && (
        <div
          className="react-loader-text-tip"
          style={{ marginTop: `${textOffset}px`, color: textColor }}
        >
          {' '}
          {text}{' '}
        </div>
      )}
    </div>
  ) : null;
};

export default Loader;

Spining​ 动画组件主要是具体的动画内容, 这里我选取了 10 余种动画进行封装, 我举一个 BallBeat 的例子:

import React, { memo } from 'react';
import Loader from '../Loader';
import { ILoadingProp } from '../type';
import './style';

export default memo(
  ({ text, style, color, textColor, size, visible }: ILoadingProp) => {
    return (
      <Loader text={text} style={style} visible={visible} textColor={textColor}>
        <div className="ball-scale">
          <div
            style={{
              backgroundColor: color,
              width: `${size}px`,
              height: `${size}px`,
            }}
          ></div>
        </div>
      </Loader>
    );
  },
);

在项目中具体使用方式如下:

import { BallPulse, BallClipRotate, SquareSpin } from '@alex_xu/react-loading';

export default () => <BallClipRotate text="H5-Dooring" />;

按需导入配置:

extraBabelPlugins: [
    [
      'babel-plugin-import',
      {
        libraryName: '@alex_xu/react-loading',
        libraryDirectory: 'es',
        camel2DashComponentName: false,
        style: true,
      },
    ],
  ],

后续会持续丰富加载动画库, 包括骨架屏动画等, 欢迎大家使用 并 star 支持~

图片

github地址: https://github.com/MrXujiang/react-loading​

责任编辑:武晓燕 来源: 趣谈前端

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK