要自定义 React 的懒加载(lazyLoad)组件,你可以遵循以下步骤:
react-router-dom
,因为懒加载功能依赖于它。如果没有安装,可以使用以下命令安装:npm install react-router-dom
LazyComponent
的 HOC:import React, { Component } from 'react';
import { Suspense, lazy } from 'react';
const LazyComponent = (importComponent) => {
const Lazy = lazy(importComponent);
return class extends Component {
render() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Lazy />
</Suspense>
);
}
};
};
export default LazyComponent;
在这个例子中,我们使用了 React.lazy()
函数来动态导入组件。fallback
属性用于在组件加载过程中显示一个占位符。
LazyComponent
来懒加载你的组件。例如,假设你有一个名为 MyComponent
的组件,你可以这样使用它:import React from 'react';
import LazyComponent from './LazyComponent';
const MyComponent = () => {
return <div>Hello, I am MyComponent!</div>;
};
export default LazyComponent(MyComponent);
App.js
文件中:import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import LazyComponent from './LazyComponent';
const Home = () => {
return <div>Home Page</div>;
};
const About = () => {
return <div>About Page</div>;
};
const MyComponent = () => {
return <div>Hello, I am MyComponent!</div>;
};
const App = () => {
return (
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/my-component" component={LazyComponent(MyComponent)} />
</Switch>
</Router>
);
};
export default App;
现在,当你访问 /my-component
路径时,MyComponent
将被懒加载。