溫馨提示×

如何自定義react lazyLoad的加載組件

小樊
81
2024-10-16 00:34:55
欄目: 編程語言

要自定義 React 的懶加載(lazyLoad)組件,你可以遵循以下步驟:

  1. 首先,確保你已經(jīng)安裝了 react-router-dom,因?yàn)閼屑虞d功能依賴于它。如果沒有安裝,可以使用以下命令安裝:
npm install react-router-dom
  1. 創(chuàng)建一個(gè)高階組件(Higher-Order Component,HOC),它將負(fù)責(zé)實(shí)現(xiàn)懶加載功能。在這個(gè)例子中,我們將創(chuàng)建一個(gè)名為 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;

在這個(gè)例子中,我們使用了 React.lazy() 函數(shù)來動態(tài)導(dǎo)入組件。fallback 屬性用于在組件加載過程中顯示一個(gè)占位符。

  1. 現(xiàn)在,你可以使用 LazyComponent 來懶加載你的組件。例如,假設(shè)你有一個(gè)名為 MyComponent 的組件,你可以這樣使用它:
import React from 'react';
import LazyComponent from './LazyComponent';

const MyComponent = () => {
  return <div>Hello, I am MyComponent!</div>;
};

export default LazyComponent(MyComponent);
  1. 最后,在你的路由配置中使用這個(gè)懶加載的組件。例如,在 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;

現(xiàn)在,當(dāng)你訪問 /my-component 路徑時(shí),MyComponent 將被懶加載。

0