要自定義 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
將被懶加載。