在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,可以看