Bootstrap

React集成Nprogress顶部进度条(效果图 + 代码实现)

「效果」

nprogress

「React 代码」

如果仅仅是想在项目中使用 nprogress顶部进度条,那么直接拷贝下面的代码就完事了

  1. 安装依赖包
npm install nprogress 
npm install hoist-non-react-statics
  1. 创建 withProgress.jsx 高阶组件
import React, { Component } from "react";
import hoistNonReactStatic from "hoist-non-react-statics";
import Nprogress from "nprogress";
import "nprogress/nprogress.css";

export const WidthProgress = (WrappedComponent) => {
  class NewComponent extends Component {
    componentWillMount() {
      Nprogress.start();
    }
    
    componentDidMount() {
      Nprogress.done();
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  }
  // 拷贝「包装组件」的静态方法到「新组件」
  hoistNonReactStatic(NewComponent, WrappedComponent);
  return NewComponent;
};

  1. 高阶组件应用
import { WidthProgress } from "./withProgress";
import Menu from "./Menu";
function App() {
  return (
    <div className='App'>
      <div className='content'>HOME</div>

      <Menu />
    </div>
  );
}

export default WidthProgress(App);

到此已经实现了开局的效果

「Nprogress 函数方法」

  • NProgress.start

    开启进度条

  • NProgress.set

    进度条设置百分比

  • NProgress.inc

    进度条增长设置数量

  • NProgress.done

    关闭进度条

  • NProgress.status

    进度条状态

「Nprogress 配置」

属性默认值备注
minimum0.08进度条初始最小量
template进度条自定义模板
easingease进度条动态效果
speed200ms时间内完成
trickletrue是否显示细流进度条
trickleRate0.02细流进度条速率
trickleSpeed800细流进度条速度
showSpinnertrue是否显示旋式进度条
parentbody进度条挂在的DOM节点

Nprogress 配置应用

import React, { Component } from "react";
import hoistNonReactStatic from "hoist-non-react-statics";
import Nprogress from "nprogress";
import "nprogress/nprogress.css";

export const WidthProgress = (WrappedComponent) => {
  // nprogress 配置项
  const processConfig = {
    trickle: false,
    showSpinner: false,
    easing: "ease",
    speed: 500,
  };
  Nprogress.configure(processConfig);

  class NewComponent extends Component {
    componentWillMount() {
      Nprogress.start();
    }

    componentDidMount() {
      Nprogress.done();
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  }
  // 拷贝「包装组件」的静态方法到「新组件」
  hoistNonReactStatic(NewComponent, WrappedComponent);
  return NewComponent;
};

;