开篇
react router功能很强大,可以根据路径配置对应容器组件。做到组件的局部刷新,接下来我会基于react实现一个简单的路由组件。
代码
自定义路由组件
import {useEffect, useState} from "react";
import React from 'react'
// 路由配置
export const MyRouter = ({children})=>{// 获取hash,当url中hash变更后会重新渲染const [hashVal] = useHash();// 获取路由组件let targetComponent = null;for (let component of children){if (component.props.path == hashVal){targetComponent = component;break;}}// 返回路由组件的内容return targetComponent ? targetComponent.props.component : "Not Found"
}
// 路由項配置
export const Route = () => null;// 获取浏览器hash hook
const useHash = ()=>{const [hash,setHash]= useState(window.location.hash);useEffect(()=>{const handleHashChange = () => {setHash(window.location.hash);};// 注册hashChange事件window.addEventListener('hashchange', handleHashChange);return () => {window.removeEventListener('hashchange', handleHashChange);};},[])let hashVal = hash;if (hash.startsWith('#')){hashVal = hash.substr(1)}return [ hashVal]
}
app.js
import './App.css';
import {MyRouter,Route} from "./component/MyRouter";const App = ()=> {return (<div><div className="sider"><a href="#page1">Page 1</a><a href="#page2">Page 2</a></div><div className="page-container"><MyRouter><Route path="page1" component ={<span>我是1号</span>} /><Route path="page2" component ={<span>我是2号</span>} /></MyRouter></div></div>)
}