React+TypeScript项目中如何正确定义组件Link路由to Prop的类型
错误原因
你代码的核心问题有两个:
- 类型引用错误:
LocationDescriptor不属于React命名空间下的类型,是react-router-dom包内置的路由类型 - 组件返回值标注错误:你把函数组件的返回值标注成了
ChildProps,和React组件实际返回的JSX元素类型不匹配
解决方案
适配react-router v6(当前主流版本)
直接使用react-router-dom导出的原生To类型,和Link组件的to属性类型完全匹配,不会出现类型冲突:
import { Link, To } from 'react-router-dom'; interface ChildProps { children: React.ReactNode to?: To } // 要么删除返回值标注让TS自动推导,要么标注为JSX.Element,不要写ChildProps export const ChildComponent = ({children, to}: ChildProps) => { return ( <> <Link to={to}/> {children} </> ) }
适配react-router v5
如果使用的是v5版本,从react-router-dom导入LocationDescriptor类型即可:
import { Link, LocationDescriptor } from 'react-router-dom'; interface ChildProps { children: React.ReactNode to?: LocationDescriptor<any> } export const ChildComponent = ({children, to}: ChildProps) => { return ( <> <Link to={to}/> {children} </> ) }
内容的提问来源于stack exchange,提问作者Sumting
相关产品推荐
相关产品推荐

