本章节主要讲解一种后台实现React-router配置的实现方案。 react-router官方文档 。
一、骨架初始化
由于React没有像Vue那样将Router单独进行封装。所以使用React进行开发时,Router的实现方案最好也用专门的路由文件进行管理,不然route要是散落在每个业务组件中,对于代码维护成本是极高的。下面我们讲解一种后台管理系统比较常见的Menu菜单和Route搭配使用的方案。
安装react-router-dom,是基于react-router操作dom实现一个路由库。
yarn react-router-dom
然后在根组件app.tsx中使用Router包裹项目骨架层。
 //   App.tsx  
import { HashRouter as Router } from  'react-router-dom'
 function   App() {
    return   (
     <div className="App">
        <Router>
            <BaseLayout/>
        </Router>
    </div>
   );
} 
接下来我们使用antd中的Layout组件实现页面基本骨架,包括Header、Navside、Content基本结构。
 //   BaseLayout.tsx 
class BaseLayout  extends React.Component<object, object>  {
    render() {
          return  (
             <Layout className="main">
                <Layout.Header className="main-header"><Header/></Layout.Header>
                <Layout className="main-content">
                    <Navside/>
                    <Layout.Content><Routes/></Layout.Content>
                </Layout>
            </Layout>
         )
    }
} 
接下来我们只需要封装两个组件。Navside菜单栏,控制路由跳转;Routes动态匹配路由,渲染当前组件。
二、全局router文件
我们先在src下新建router文件夹,新建index.tsx文件存放页面路由信息:
const Routes: MenuItem[] =  [
    { key:  '/main/index', title: '首页', icon: 'bank', component: 'HomeData'  },
    { key:  '/main/table', title: '表格', icon: 'book', component: 'BaseTable'  },
    { key:  '/main/message', title: '消息', icon: 'bulb', component: 'Messsage'  },
    { key:  '/main/auth', title: '权限', icon: 'bug', component: 'Auth'  },
    { key:  '/main/staff', title: '员工', icon: 'audio', component: 'Staff'  },
    {
        key:  '/main/setting' ,
        title:  '设置' ,
        icon:  'rocket' ,
        subs: [
            {
                key:  '/main/setting/usercenter' ,
                title:  '个人中心' ,
                component:  'Usercenter' ,
            },
            {
                key:  '/main/setting/expand' ,
                title:  '功能扩展' ,
                component:  'Expand' ,
            },
        ],
    },
] 
 View Code 
 
                    
            
                
查看更多关于从零搭建React+TypeScript的后台项目(二)的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did223470