[英]How to pass an interface as a prop in React w/ TypeScript?
I'd like to pass an object into my functional component.我想将 object 传递给我的功能组件。 This object has a consistent formatting so I'm using an interface.
这个 object 具有一致的格式,所以我使用的是接口。 Here's the functional component parameters line:
这是功能组件参数行:
interface Option { value: any, label: string; }
export default function JSelect(options: Option[], primaryColor: string, textColor: string) {
and here's the usage of the component:这是组件的用法:
interface Option { value: any, label: string; }
const letteroptions: Option[] = [
{ value: 0, label: 'Ab' },
{ value: 1, label: 'A' },
{ value: 2, label: 'Bb' },
{ value: 3, label: 'B' },
{ value: 4, label: 'C' },
{ value: 5, label: 'Db' },
{ value: 6, label: 'D' },
{ value: 7, label: 'Eb' },
{ value: 8, label: 'E' },
{ value: 9, label: 'F' },
{ value: 10, label: 'Gb' },
{ value: 11, label: 'G' }
];
<JSelect options={letteroptions} primaryColor='#87c6bb' textColor='#2c3f43' />
The types are defined exactly the same, so I'm unsure why this isn't working.类型的定义完全相同,所以我不确定为什么这不起作用。 Here's the error I get:
这是我得到的错误:
(property) options: Option[]
(属性)选项:Option[]
Type '{ options: Option[];
输入'{选项:选项[]; primaryColor: string;
原色:字符串; textColor: string;
文本颜色:字符串; }' is not assignable to type 'IntrinsicAttributes & Option[]'.
}' 不可分配给类型 'IntrinsicAttributes & Option[]'。 Property 'options' does not exist on type 'IntrinsicAttributes & Option[]'.ts(2322)
类型“IntrinsicAttributes & Option[]”.ts(2322) 上不存在属性“选项”
Instead of using multiple arguments.而不是使用多个 arguments。 Your props should be fields of the first argument of your component.
你的 props 应该是组件第一个参数的字段。 You should define your component as shown below instead.
您应该改为如下所示定义您的组件。
interface JSelectProps {
options: Option[];
primaryColor: string;
textColor: string;
}
export default function JSelect({
options,
primaryColor,
textColor,
}: JselectProps) {}
If you want to learn more about typing react components.如果你想了解更多关于输入 react 组件的信息。 Checkout the react typescript cheatsheet
查看反应 typescript 备忘单
export default function JSelect(options: Option[], primaryColor: string, textColor: string) {
If JSelect is a component, then components only receive one argument, not multiple.如果 JSelect 是一个组件,那么组件只接收一个参数,而不是多个。 That argument is an object with the individual props.
该参数是带有单独道具的 object。 So the type for this should be:
所以这个类型应该是:
interface JSelectProps {
options: Option[],
primaryColor: string,
textColor: string
}
export default function JSelect(props: JSelectProps) {
// ... do stuff with props.options, props.primaryColor, props.textColor
}
If you wish, you can use destructuring to break the props object up into individual variables:如果您愿意,可以使用解构将道具 object 分解为单个变量:
export default function JSelect({ options, primaryColor, textColor }: JSelectProps) {
// ... do stuff with options, primaryColor, textColor
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.