「效果」
「React 代码」
如果仅仅是想在项目中使用 nprogress顶部进度条,那么直接拷贝下面的代码就完事了
- 安装依赖包
npm install nprogress
npm install hoist-non-react-statics
- 创建 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;
};
- 高阶组件应用
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 配置」
属性 | 默认值 | 备注 |
---|---|---|
minimum | 0.08 | 进度条初始最小量 |
template | 进度条自定义模板 | |
easing | ease | 进度条动态效果 |
speed | 200ms | 时间内完成 |
trickle | true | 是否显示细流进度条 |
trickleRate | 0.02 | 细流进度条速率 |
trickleSpeed | 800 | 细流进度条速度 |
showSpinner | true | 是否显示旋式进度条 |
parent | body | 进度条挂在的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;
};