1. 程式人生 > 其它 >React使用配置檔案生成路由(類似於vue的路由配置)

React使用配置檔案生成路由(類似於vue的路由配置)

廢話不多說,直接上程式碼,後面會附上專案地址

1、建立react工程,執行 npm instal [email protected] --save

2、在src裡面新建router資料夾,資料夾目錄如下

3、在router資料夾裡面新建index.jsx

import React, { Component } from 'react';
import { Route, Switch, Redirect, HashRouter, withRouter } from "react-router-dom";

import Config from './config'

class Router extends Component {

  //遞迴生成路由檔案
  generateRoute(ele) {
    if (ele.children) {
      if (ele.component) {
        return (
          <Route key={ele.name} path={ele.path} render={() => (
            <ele.component>
              {
                ele.children.map((item) => {
                  return this.generateRoute(item)
                })
              }
            </ele.component>
          )}>
          </Route>
        )
      } else {
        return (
          <Route key={ele.name} render={() => (
            ele.children.map((item) => {
              return this.generateRoute(item)
            })
          )}>
          </Route>
        )
  
      }
  
    }
  
    if (ele.redirect) {
      return <Route exact key={ele.name} path={ele.path} render={
        () => (
          <Redirect to={ele.redirect} />)}>
      </Route>
    } else {
      return <Route exact key={ele.name} path={ele.path} component={ele.component} />
    }
  
  }

  render() {
    return (
      <HashRouter>
        <Switch>
  
          {
            Config.map(item => {
              return this.generateRoute(item)
            })
          }

        </Switch>
      </HashRouter>
    );
  }
}

export default withRouter(Router);

4、在router資料夾裡面新建config.jsx

import Layout from '../views/layout/layout';

import A from '../views/pages/a';
import B from '../views/pages/b';
import Login from '../views/pages/login';

const router = [
  {
    path: '/',
    name: "Login",
    auto: false,
    component: Login,
  },{
    redirect: '/Layout',
    path: '/Layout',
    component: Layout,
    name: "Layout",
    auto: true,
    children: [
      {
        path: "/Layout/A",
        name: "介紹",
        auto: true,
        component: A,
      }, {
        path: "/Layout/B",
        name: "設計原則",
        auto: true,
        component: B,
      }
    ]
  }
]

export default router;

  5、刪除src資料夾裡面的app.js、app.css檔案,index.js檔案修改如下:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

import Router from "./router";
import { BrowserRouter } from 'react-router-dom';

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <Router />
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);

  6、在src裡面新建views資料夾,然後新建幾個頁面,在config.js資料夾裡面引入就可以了,我建的資料夾在專案在github裡面

7、github地址https://github.com/lzx-cloud/examples-h5/tree/main/react-router