简单实现一个 react-router
核心步骤如下:
先把 URL 解析 path 出来
然后匹配 routes 数组, 找到 path 相同, 返回出去即可
这时候会有一个问题, 页面没法更新数据, 所以用 onhashchange 监听
重新渲染
提供执行钩子, 也就是写路由文件的时候, 页面设置成一个函数, 然后方便执行到的时候, 进行数据更新等处理
最终代码
- 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>
- }
- Windows.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--
来源: http://www.jianshu.com/p/32402f00eeb8