英文:
Problem with typescript error when create react generic component
问题
最近,在使用React时,我遇到了一些问题。当我调用我的React通用组件BaseBlock时,我已经提供了一个类型,但是TypeScript报错说:
期望0个类型参数,但实际提供了1个.ts(2558)
我想要问如何解决这种情况。
这是我的BaseBlock组件:
import React from 'react';
interface Props<T> {
id?: string;
items?: T[];
children?: (item: T, index: number) => React.ReactNode;
parentId?: string;
contentId?: string[];
}
const BaseBlock = React.forwardRef(function BaseBlock<T>(
{ items, children }: React.PropsWithChildren<Props<T>>,
ref: React.ForwardedRef<HTMLDivElement>
): React.ReactElement | null {
return (
<div data-testid="base-block" ref={ref}>
{items && children && items.map(children)}
</div>
);
});
export type BaseBlockProps<T> = React.PropsWithRef<Props<T>>;
export default BaseBlock;
我为我的组件提供了字符串类型。期望没有错误并渲染这个组件。它的确渲染了,但TypeScript给我报错:
期望0个类型参数,但实际提供了1.ts(2558)
我认为问题出在我为我的组件提供了<string>
类型,但这个组件不应该使用类型,它期望不带类型参数的组件。那么,我该如何解决这个问题?
英文:
Recently, I encountered some issues while using React. when I called my react generic component, BaseBlock.
I had already provided a type, but TypeScript threw an error saying
>Expected 0 type arguments, but got 1.ts(2558)
I would like to ask how to solve this situation.
const items = ['test1', 'test2', 'test3'];
const renderComp = (item: any) => {
return <div>{item}</div>
}
<BaseBlock<string> items={items}>{renderRow}</BaseBlock>
^
error
This is my BaseBlock component
import React from 'react';
interface Props<T> {
id?: string;
items?: T[];
children?: (item: T, index: number) => React.ReactNode;
parentId?: string;
contentId?: string[];
}
const BaseBlock = React.forwardRef(function BaseBlock<T>(
{ items, children }: React.PropsWithChildren<Props<T>>,
ref: React.ForwardedRef<HTMLDivElement>
): React.ReactElement | null {
return (
<div data-testid="base-block" ref={ref}>
{items && children && items.map(children)}
</div>
);
});
export type BaseBlockProps<T> = React.PropsWithRef<Props<T>>;
export default BaseBlock;
I give my component string type. Excepted no error and render this component. It just render, but typescript give me error
>Expected 0 type arguments, but got 1.ts(2558)
I think it is that I give the <string> type for my comp, but this comp should not use type, it excepted 0 argument on this comp, so how can I solved?
答案1
得分: 1
我通过 @Linda Paiste 的评论解决了这个问题,并参考了这个 问题。
最后,我使用了全局类型扩充来解决它。
declare module 'react' {
function forwardRef<T, P = {}>(
render: (props: P, ref: React.Ref<T>) => React.ReactElement | null
): (props: P & React.RefAttributes<T>) => React.ReactElement | null;
}
英文:
I solved this problem by @Linda Paiste comment
and reference this question.
Finally, I used global type augmentation and solved it.
declare module 'react' {
function forwardRef<T, P = {}>(
render: (props: P, ref: React.Ref<T>) => React.ReactElement | null
): (props: P & React.RefAttributes<T>) => React.ReactElement | null;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论