如何将React组件传入helper工具函数并正确声明TypeScript类型
问题解决方法
你遇到的TS报错有两个核心原因:
- 未导入React提供的组件类型,直接使用了不存在的全局类型
Component做类型注解 - JSX组件调用时和参数大小写不匹配,同时React要求自定义组件在JSX中使用必须首字母大写,否则会被识别为原生HTML标签
修复步骤
1. 修正helpers.ts文件
首先导入React的ComponentType类型,同时调整参数名和类型注解:
// helpers.ts import type { ComponentType } from 'react'; import { LINKS } from '../constants'; // 可根据你的实际业务调整Props类型,这里直接复用LINKS的元素类型保证类型匹配 type LinkProps = typeof LINKS[number]; // 参数首字母大写,符合JSX调用规范 const createLinks = (Component: ComponentType<LinkProps>) => { return LINKS.map((props) => ({ content: <Component {...props} />, id: props.id })); };
如果你使用的是React17以下的版本,需要在helpers.ts顶部额外导入React以支持JSX语法:
import React from 'react';
2. 修正component.tsx的语法问题
原代码中List标签未正确闭合,调整如下:
// component.tsx import { List, SpecialLink } from '../components'; import { createLinks } from '../helpers'; const LinkList = () => { const links = createLinks(SpecialLink); return <List items={links} />; }
通用扩展(可选)
如果需要让createLinks工具函数支持传入不同Props类型的组件,可以改写为泛型版本:
import type { ComponentType } from 'react'; // 泛型版本,支持传入自定义的链接列表和对应组件 const createLinks = <T extends { id?: string | number }>( Component: ComponentType<T>, linkList: T[] ) => { return linkList.map((props) => ({ content: <Component {...props} />, id: props.id })); }; // 调用方式 // const links = createLinks(SpecialLink, LINKS);
内容的提问来源于stack exchange,提问作者Jeff Stein
相关产品推荐
相关产品推荐

