码迷,mamicode.com
首页 > 其他好文 > 详细

react RouterView

时间:2020-04-30 13:35:29      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:import   exp   path   component   直接   port   ops   router   拼接   

import React from "react";
import { Route } from "react-router";
import { BrowserRouter as Router } from "react-router-dom";
// 路径拼接
import {join} from ‘path‘;

/**
 * 子路由定义
 * @param props
 * @returns {*}
 * @constructor
 */
const ChildRouteList = props => {
  const { children, parentPath } = props;
  return <>
    {children.map(({path, component: Component, children}) => {
      return <Route path={join(parentPath, path)} key={path}>
        <Component/>
        {children && <ChildRouteList parentPath={join(parentPath, path)} children={children}/>}
      </Route>
    })}
  </>
};

/**
 * RouterView组件
 * 以后只要直接写路由就可以了
 * 总的来说就是递归写几层循环
 * @param props
 * @returns {*}
 * @constructor
 */
export default function RouterView(props) {
  const { routes } = props;
  return <Router>
    {routes.map(({path, component: Component, children}) => {
      return <Route path={path} key={path}>
        <Component/>
        <ChildRouteList parentPath={path} children={children}/>
      </Route>
    })}
  </Router>
}

/**
 * 路由定义
 */
import React from "react";

export default  [
  {
    path: ‘/‘,
    component: props => <div>
      this is /
    </div>,
    children: [
      {
        path: ‘/web‘,
        component: props => <span>/‘s child 1</span>
      },
      {
        path: ‘/php‘,
        component: props => <span>/‘s child 2</span>
      },
    ]
  }
]

react RouterView

标签:import   exp   path   component   直接   port   ops   router   拼接   

原文地址:https://www.cnblogs.com/tujw/p/12808187.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!