【发布时间】:2022-01-07 11:14:18
【问题描述】:
问题:
可以在函数组件中使用 React 路由器钩子来检索当前路由。
但是,我找不到类组件的任何参考。
案例:
我有一个导航菜单,我想通过根据当前状态切换 css 类来跟踪当前路由以在前端突出显示它。
导航摘录:
import React, { Component, Fragment } from 'react';
import { Link } from 'react-router-dom';
...
export default class Nav extends Component {
...
render = (): JSX.Element => {
return (
<>
{/* Current: "border-green-500 text-gray-900" */}
{/* Default: "border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700" */}
<Link to="/"
className="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium"
>
Home
</Link>
</>
);
}
}
问题:
有什么方法可以在 react 类组件中实现这个目标吗?
预期答案:
- 参考工作示例
- 代码 sn-p
- 解释为什么这不起作用
- 替代解决方案
提前谢谢你!
感谢@genius fox dev,这个解决方案确实对我有用!
解决方案:
{/* Current: "border-green-500 text-gray-900" */}
{/* Default: "border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700" */}
<NavLink // from 'react-router-dom'
to="/"
className={
( {isActive} ) => ( isActive
? 'border-green-500 text-gray-900'
: 'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700'
).concat( ' inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium' )
}
>
Home
</NavLink>
【问题讨论】:
标签: javascript reactjs react-router react-component