React-Router实现Tag封装

在React-Router中Link无法指定生成的元素类型,那么我们可以封装一个,就可以实现Vue-router中tag的功能。

一下代码中是有了react中的样式组件,需要安装:

yarn add style-component -s

封装代码:

import React from 'react'
import {  NavLink, Route, withRouter } from 'react-router-dom'
import styled from 'styled-components'


// 身上既有路由属性,又有了OwnLink的属性
const OwnLinkItem = (props) => {
    // 要渲染成的tag
    let Tag = props.tag || 'a'
    // 要加的类名
    let _class = props.className || ''
    let _activeClassName = props.activeClassName || 'active'
    // 判断是否加active
    let isActive = props.exact ? props.location.pathname === 
    props.to: props.location.pathname.startsWith(props.to)
    let className = (props.nav && isActive )? _class + ' ' + _activeClassName : _class
    return <Tag className = {className} onClick = {() => {
            props.history.push(props.to) }}>{props.children}
        </Tag>
}
// 自己实现的Link组件,因为内部需要调用history的路由相关api,
//而Link组件又不是一个路由组件(会自动包Route,并能得到context中的路由相关属性),
//所以想要使用到这些api,需要利用withRouter的高阶组件来进行处理
export const OwnLink = props => {   
    let Item = withRouter(OwnLinkItem)
    return (
        <Item {...props}/>
    )
}
// 自己封装的NavLink属性,既可以使用tag属性,又可以动态的设置activeClass
export const OwnNavLink = props => {
    let Item = withRouter(OwnLinkItem)
    return (
        <Item {...props} nav/>
    )
}

// 为react-router提供的NavLink加样式
export const ActiveNavLink = styled(NavLink)`
    &.active {
        color: tomato;
    }
    &.selected {
        color: blue;
    }
    color: #333;

`
// 为自己的OwnNavLink添加样式
export const ActiveOwnNavLink = styled(OwnNavLink)`
    &.active {
        color: tomato;
    }
    &.selected {
        color: blue;
    }
    color: #333;
`



使用:

// 引入上面封装的函数
import {OwnActiveNavLink} from './utils'
 
<OwnActiveNavLink  tag = 'li' to = '/todoList'>TodoList</OwnActiveNavLink>  
<OwnActiveNavLink activeClassName = 'ok' tag = 'li' second to'/user'>User</OwnActiveNavLink>

总结:关于代码实现注释里写的很明白,导入到路由文件中解构出来就可以使用,如果你还不会使用React-Router,可以看

React-Router用法详解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值