我目前正在使用 TypeScript 和 ReactRouter 开发一个 React 项目。 。在某些地方我使用 NavLink像这样的钩子(Hook):
const {itemPath} = props // itemPath is a string
return (
<Router>
<div>
<ul>
<li>
<NavLink
to="/"
isActive={(match: any, location: any): boolean => {
if (!match) {
return false;
}
if (location.pathname === itemPath) return true;
return false;
>
Home
</NavLink>
</li>
...
如您所见,在 isActive
中函数我只是返回 true
如果实际路径( location.pathname
)也相等 itemPath
来自 Prop 。
这里的问题是我使用 any
isActive
的两个参数的类型回调:match
和location
。因此,我决定考虑为它们分配正确的类型,但文档说使用这种使用泛型的类型定义:
isActive?<Params>(match: match<Params>, location: Location<History<HistoryLocationState = History.PoorMansUnknown>.PoorMansUnknown>): boolean
不幸的是,我根本不知道如何输入我的论点。有人有什么想法吗?
最佳答案
我会使用 useHistory
或 useLocation
钩子(Hook)。
const {itemPath} = props // itemPath is a string
const location = useLocation()
// or const { location } = useHistory()
return (
<Router>
<div>
<ul>
<li>
<NavLink
to="/"
isActive={() => itemPath === location.pathname}
>
Home
</NavLink>
</li>
// ... rest
如果您想输入参数,当前定义是:
isActive?<Params extends { [K in keyof Params]?: string }>(
match: match<Params>,
location: H.Location<S>,
): boolean;
我相信如果省略参数, typescript 可以正确推断参数的类型。所以这样的事情就足够了:
isActive={(match, location) => {
if (!match) {
return false
}
if (location.pathname === itemPath) return true
return false
}}
来源:https://reacttraining.com/react-router/web/api/Hooks/uselocation
关于reactjs - react 路由器 : Add types to NavLink isActive() function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61059341/