手写实现react-router当中的link组件

434 阅读1分钟
/* eslint-disable no-script-url */
/* eslint-disable jsx-a11y/anchor-is-valid */
import {withRouter} from "react-router-dom"
import React from 'react';

const Link = (props) => {
    return (
        <a href="javascript:;"  onClick={()=>{
            props.history.push(props.to)
        }}>{props.children}</a>
    );
};

const Letx = withRouter(Link)
export default Letx

首先,我们要知道link是什么?

它实际上就相当于是a标签,只不过是无刷新进行跳转的a标签

然后我们这里是用props.history.push 来进行实现的,需要在使用组件时 传入一个 to属性

并且,

你需要在父组件内,把 BrowserRouter 、Route 的引用写完整

最后由于。当前标签 并不是直接写在Route上的,所以需要withRouter高阶组件来进行一层包装

注:这里面的