英文:
Typescript error when extending a forwardRef component e.g) ListItem.Placeholder = ListItemPlaceholder
问题
我想将ListItemPlaceholder
放在ListItem
组件下面。ListItem
在其中使用了forward ref。但是尽管我已经在文件末尾执行了ListItem.Placeholder = ListItemPlaceholder
,但typescript仍然报错:
TS2322:类型'ForwardRefExoticComponent<Props & RefAttributes
示例:
type ListItemComponent = ForwardRefExoticComponent<Props> & {
Placeholder: typeof ListItemPlaceholder;
};
export const ListItem: ListItemComponent = forwardRef<
HTMLDivElement,
Props
>((props, ref) => {
//.....
return <div ref={ref}/>;
})
const ListItemPlaceholder: FunctionComponent = () => {
return <div/>;
};
ListItem.Placeholder = ListItemPlaceholder;
英文:
I want to put the ListItemPlaceholder
under the ListItem
component. The ListItem
uses forward ref in it. But the typescript complains about this even though I already do this: ListItem.Placeholder = ListItemPlaceholder
at the end of the file.
TS2322: Type 'ForwardRefExoticComponent<Props & RefAttributes<HTMLDivElement>>' is not assignable to type 'ListItemComponent'. Property 'Placeholder' is missing in type 'ForwardRefExoticComponent<Props & RefAttributes<HTMLDivElement>>' but required in type '{ Placeholder: FunctionComponent<{}>; }'.
Example:
type ListItemComponent = ForwardRefExoticComponent<Props> & {
Placeholder: typeof ListItemPlaceholder;
};
export const ListItem: ListItemComponent = forwardRef<
HTMLDivElement,
Props
>((props, ref) => {
//.....
return <div ref={ref}/>
}))
const ListItemPlaceholder: FunctionComponent = () => {
return <div/>
};
ListItem.Placeholder = ListItemPlaceholder
答案1
得分: 1
这是一个类型不匹配的问题。也许问题出在占位符类型上。
你可以进行以下更改并尝试。
const ListItemPlaceholder: FunctionComponent = () => {
return <div/>
};
type ListItemComponent = ForwardRefExoticComponent<Props> & {
Placeholder: typeof ListItemPlaceholder;
};
export const ListItem: ListItemComponent = forwardRef<
HTMLDivElement,
Props
>((props, ref) => {
//.....
return <div ref={ref}/>
});
ListItem.Placeholder = ListItemPlaceholder;
在使用之前,你应该始终声明一个变量或类型。
英文:
This is a type-mismatch problem. And maybe the problem is with the placeholder type.
You can make these changes and try.
const ListItemPlaceholder: FunctionComponent = () => {
return <div/>
};
type ListItemComponent = ForwardRefExoticComponent<Props> & {
Placeholder: typeof ListItemPlaceholder;
};
export const ListItem: ListItemComponent = forwardRef<
HTMLDivElement,
Props
>((props, ref) => {
//.....
return <div ref={ref}/>
}));
ListItem.Placeholder = ListItemPlaceholder;
You should always declare a variable or type before it is used.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论