javaScript让前端飞Web前端之路

react-实现一个简单的页面转跳路由

2019-05-30  本文已影响43人  反者道之动001

简单实现一个react-router

核心步骤如下:

最终代码

const Main = (root: HTMLElement | null) => {
   let getPath = (url: string): string => {
      let href = url.split('#')[1]
      return href ? href.split('?')[0] : '/'
   }
   let getView = (urlPath: string) => {
      let pageInfo = routes.find((route: Troute) => route.path === urlPath)
      let pagePath = pageInfo ? pageInfo.path : ''
      return <div>
         {
            routes.map(e => {
               let view: ReactElement | Boolean
               if (e.path === pagePath) {
                  view = e.page()
               } else {
                  view = false
               }
               return view
            }).filter(e => e)
         }
      </div>
   }
   window.onhashchange = (e: HashChangeEvent) => {
      ReactDOM.render(getView(getPath(e.newURL)), root)
   }
   ReactDOM.render(getView(getPath(location.href)), root)
}

Main(
   document.getElementById('root')
)

类型

import { ReactElement } from 'react'
export interface Troute {
    path: string,
    page: () => ReactElement
}

具体代码查看我的项目【可视化布局 纯css布局 Layout-UI 】
GITHBU: https://github.com/0123cf/layout-ui
自动化可视化布局官网: http://layoutui.pro/

--END--

上一篇下一篇

猜你喜欢

热点阅读