React+TypeScript报错:类型上不存在属性'data',求问题排查
React+TypeScript组件传参报错:Property 'data' does not exist on type 'IntrinsicAttributes & Product[]'
报错发生在<Testing data={products} />的组件调用处,代码示例如下:
export default function FilterableProductTable() { const products: Product[] = [ { category: "Fruits", price: "$1", stocked: true, name: "Apple" }, { category: "Fruits", price: "$1", stocked: true, name: "Dragonfruit" }, { category: "Fruits", price: "$2", stocked: false, name: "Passionfruit" }, { category: "Vegetables", price: "$2", stocked: true, name: "Spinach" }, { category: "Vegetables", price: "$4", stocked: false, name: "Pumpkin" }, { category: "Vegetables", price: "$1", stocked: true, name: "Peas" }, ]; return ( <> <Testing data={products} /> </> ); } interface Product { category: string; price: string; stocked: boolean; name: string; } function Testing(data: Product[]) { return <p>{data[0].category}</p>; }
问题原因
React组件的参数必须是props对象,而非单个值。当前Testing组件直接声明接收Product[]类型的参数,但在JSX调用时,React会把你传入的data属性包装成一个props对象(包含IntrinsicAttributes和自定义属性)传递给组件,导致类型不匹配——组件期望接收数组,实际收到的是带data属性的对象,因此触发类型错误。
至于TypeScript Playground能运行,是因为那里没有React环境,Testing会被当作普通函数处理,直接传入数组就能执行,不会触发React的props校验逻辑。
修复方案
- 先定义
Testing组件的props接口,明确接收的属性:
interface TestingProps { data: Product[]; }
- 修改
Testing组件,让它接收props对象,可通过解构获取data:
function Testing({ data }: TestingProps) { return <p>{data[0].category}</p>; }
或者不使用解构,直接通过props对象访问:
function Testing(props: TestingProps) { return <p>{props.data[0].category}</p>; }
内容的提问来源于stack exchange,提问作者AnubisTyrant
相关产品推荐
相关产品推荐

