我正在使用React和TypeScript,并试图将一些数据传递给子组件,并在子组件中使用它。但是我得到了错误,我不能理解为什么会发生这种情况,以及如何修复它。我也是TypeScript的初学者。
这是我的父组件
import * as React from "react";
import ChildComponent from "./ChildComponent";
const data = [
{
title: "A",
id: 1,
},
{
title: "B",
id: 1,
},
];
const ParentComponent = () => {
return (
<ChildComponent items={data} />
)
}
export default ParentComponent;
以下是项目的父组件中的错误
(JSX attribute) items: {
title: string;
id: number;
}[]
Type '{ items: { title: string; id: number; }[]; }' is not assignable to type 'IntrinsicAttributes'.
Property 'items' does not exist on type 'IntrinsicAttributes'.ts(2322)
在常规的react和es6中,我可以在子组件中使用这个道具,如下所示:
const ChildComponent = (props) => {
return (
<div>
{props.items.map((item) => (
<p to={item.title}></p>
))}
</div>
)
}
但是如果它是TypeScript的话会在子组件中使用这个道具吗?
发布于 2020-04-26 04:23:40
您需要指定子组件需要的道具类型。例如:
interface Item {
title: string;
id: number;
}
interface ChildComponentProps {
items: Item[]
}
const ChildComponent: React.FC<ChildComponentProps> = (props) => {
return (
<div>
{props.items.map((item) => (
<p to={item.title}></p>
))}
</div>
)
}
发布于 2020-04-26 04:32:20
如果道具可以为空,则在回复中添加一个问号。
interface ChildComponentProps {
items?: Item[]
}
https://stackoverflow.com/questions/61432089
复制相似问题