如何为作为prop传入的React Component设置对应类型
解决方案
你传入的component为合法React组件(包含函数组件、类组件),可直接使用React内置的ComponentType类型定义,适配你当前react-router-dom v5写法的步骤如下:
- 导入对应类型:
import type { ComponentType } from 'react'; // 若需要严格约束组件接收的路由参数类型,可额外导入下方类型 import type { RouteComponentProps } from 'react-router-dom';
- 补全
AppProps接口定义:
interface AppProps { path: string, isPrivate: boolean, // 通用写法:兼容所有可接收路由props的组件 component: ComponentType<any> // 严谨写法:明确约束组件需接收路由相关props // component: ComponentType<RouteComponentProps> }
你现有代码中将component重命名为首字母大写的Component的写法符合React组件渲染规范,不需要额外修改。
内容的提问来源于stack exchange,提问作者Atlante Avila
相关产品推荐
相关产品推荐

