React之自定义路由组件

开篇

        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>
    )
}

实现效果

认证功能扩展

const MyRouter = ({children})=>{

    // 获取hash,当url中hash变更后会重新渲染
    const [hashVal] = useHash();

    const [login] = useAuth();
    // 获取路由组件
    let targetComponent = null;
    for (let component of children){
        const needAuth = component.props.auth;
        if (component.props.path == hashVal && (!needAuth || needAuth && login)){
            targetComponent = component;
            break;
        }
    }
    // 返回路由组件的内容
    return targetComponent ? targetComponent.props.component : "not found";

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值