React@16.x(50)路由v5.x(15)源码(7)- 实现 Link 和 NavLink

1,Link

作用:最终渲染为 <a> 标签,点击跳转对应路由时不刷新页面。

1.1,注意点

1,Link.to 属性,除了传递 string 之外,还可以传递 location 对象。

2,最终渲染的路由链接中,是包括 basename 的。

1.2,实现

import React from "react";
import ctx from "../react-router/RouterContext";
import { parsePath } from "history";

export function Link(props) {
    const { to, ...rest } = props;
    return (
        <ctx.Consumer>
            {(value) => {
                let _location = {};
                if (typeof to === "object") {
                    _location = to;
                } else {
                    // 将路径字符串,转为 location 对象。
                    _location = parsePath(to);
                }
                // 通过 location 对象创建一个可用于 a 标签的链接(会自动拼接 basename)。
                const _href = value.history.createHref(_location);
                return (
                    <a
                        href={_href}
                        {...rest}
                        onClick={(e) => {
                            e.preventDefault();
                            value.history.push(_location);
                        }}
                    >
                        {props.children}
                    </a>
                );
            }}
        </ctx.Consumer>
    );
}

2,NavLink

2.1,注意点

相比较 Link 组件,NavLink 组件会在路由匹配时,对生成的 <a> 标签添加 active 类名(类名)。

匹配规则受 toexactstrictsensitive 等属性影响。

2.2,实现

import React from "react";
import { parsePath } from "history";
import { Link } from "./Link";
import ctx from "../react-router/RouterContext";
import matchPath from "../react-router/matchPath";

export function NavLink(props) {
    const { activeClass = "active", exact = false, strict = false, sensitive = false, ...rest } = props;
    return (
        <ctx.Consumer>
            {({ location }) => {
                let _location = {};
                if (typeof props.to === "object") {
                    _location = props.to;
                } else {
                    // 将路径字符串,转为 location 对象。
                    _location = parsePath(props.to);
                }
                const matched = matchPath(_location.pathname, location.pathname, { exact, strict, sensitive });
                if (matched) {
                    return <Link className={activeClass} {...rest}></Link>;
                } else {
                    return <Link {...rest}></Link>;
                }
            }}
        </ctx.Consumer>
    );
}

以上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

下雪天的夏风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值