[英]TypeScript types for React component where prop is an array of objects?
My React component has a prop called propWhichIsArray
which will be an array of objects.我的 React 组件有一个名为propWhichIsArray
的道具,它将是一个对象数组。 These objects will have an id
which is an ID and text
which is a string.这些对象将具有一个作为 ID 的id
和一个作为字符串的text
。 How can you type this with TypeScript?你怎么能用 TypeScript 输入这个?
type Props = {
propWhichIsArray: {
id,
text: string;
}[]
};
const Component: React.FC<[Props]> = ({ propWhichIsArray }) => {
//
Im getting an error:我收到一个错误:
Property 'propWhichIsArray' does not exist on type '[Props] & { children?: ReactNode;属性 'propWhichIsArray' 不存在于类型'[Props] & { children?: ReactNode; }'. }'。 TS2339 TS2339
The main issue is that you're doing React.FC<[Props]>
instead of React.FC<Props>
.主要问题是您正在做React.FC<[Props]>
而不是React.FC<Props>
。 With the square brackets, you're creating a tuple type, whose's zeroth element is of type Props, and then you're having that tuple be the props of your component.使用方括号,您将创建一个元组类型,其第零个元素的类型是道具,然后您将让该元组成为组件的道具。
interface Props {
propWhichIsArray: {
id: ID; // I assume ID is defined elsewhere
text: string;
}[]
}
const Component: React.FC<Props> = ({ propWhichIsArray }) => {
If this data in the array is being used in other places, you may want to pull it out to its own interface:如果数组中的这些数据正在其他地方使用,您可能希望将其拉出到自己的接口:
interface Thingamajig {
id: ID;
text: string;
}
interface Props {
propWhichIsArray: Thingamajig[];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.