猿问

使用React Router通过边栏导航动态呈现组件的更简单方法

当前正在本教程中学习如何使用React Router https://reacttraining.com/react-router/web/example/sidebar创建侧边栏导航系统


我计划有多个路由,所以这意味着我必须继续导入路由并将其添加到routes阵列中。是否有一种聪明/正确的方式来动态加载它们?


我所有的组件都在我的/Views文件夹中。


App.js


import React, { Component } from 'react';

import SideBar from './components/SideBar/SideBar';

import MainContent from './components/MainContent/MainContent';

import { BrowserRouter as Router,

} from 'react-router-dom';



// Import all components here

import Button from './components/Views/Button/Button';

import Color from './components/Views/Color/Color';

import Card from './components/Views/Card/Card';

import Filter from './components/Views/Filter/Filter';


const routes = [

  {

    path: "/",

    name: 'home',

    exact: true,

    main: () => <h2>Home</h2>

  },

  {

    path: "/button",

    name: 'Button',

    main: () =>  <Button />

  },

  {

    path: "/color",

    name: 'Color',

    main: () =>  <Color />

  },

  {

    path: "/card",

    name: 'Card',

    main: () =>  <Card />

  },

  {

    path: "/filter",

    name: 'Filter',

    main: () =>  <Filter />

  },

];


class App extends Component {

  render() {

    return (

      <Router>

        <div className="ds-container">

          <SideBar routes={routes} />

          <MainContent routes={routes} />

        </div>

      </Router>

    );

  }

}


export default App;


守着星空守着你
浏览 346回答 2
2回答

慕工程0101907

由于您使用的是内部使用webpack的create-react-app,因此可以查看require-context。这将帮助您动态导入与某个正则表达式匹配的文件夹中的所有文件。(例如:以.jsx / .js结尾)但是,我建议您反对:您永远不会知道您目前正在适应的路线。这可能会降低代码的可读性。您可能还必须将组件的映射(path在Route中)连同组件本身一起导出。为了避免所有这些情况,您可以index.js在Views组件中简单地创建一个文件,该文件将需要您创建的任何新的路由组件,并返回在App.js文件中形成的最终数组。因此,本质上是/Views/index.js:// Import all components hereimport Button from './components/Views/Button/Button';import Color from './components/Views/Color/Color';import Card from './components/Views/Card/Card';import Filter from './components/Views/Filter/Filter';const routes = [&nbsp; {&nbsp; &nbsp; path: "/",&nbsp; &nbsp; name: 'home',&nbsp; &nbsp; exact: true,&nbsp; &nbsp; main: () => <h2>Home</h2>&nbsp; },&nbsp; {&nbsp; &nbsp; path: "/button",&nbsp; &nbsp; name: 'Button',&nbsp; &nbsp; main: () =>&nbsp; <Button />&nbsp; },&nbsp; {&nbsp; &nbsp; path: "/color",&nbsp; &nbsp; name: 'Color',&nbsp; &nbsp; main: () =>&nbsp; <Color />&nbsp; },&nbsp; {&nbsp; &nbsp; path: "/card",&nbsp; &nbsp; name: 'Card',&nbsp; &nbsp; main: () =>&nbsp; <Card />&nbsp; },&nbsp; {&nbsp; &nbsp; path: "/filter",&nbsp; &nbsp; name: 'Filter',&nbsp; &nbsp; main: () =>&nbsp; <Filter />&nbsp; },&nbsp; // add new routes here];export default routes;在SideBar.js中:import routes from 'path/to/views/Views';//rest of your code to render the routes.这样,您可以清理App.js中的代码,并且还可以有效地分离各个组件的问题。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答