【发布时间】:2021-02-03 12:58:58
【问题描述】:
我正在尝试将 ref 转发到不带任何道具的 Typescript 组件。当我使用React.forwardRef 时,它需要两个参数:props 和 ref。我的组件不使用道具。如何声明我的组件没有 linting 或编译错误?
现在我有:
// this says "props is declared but its value is never used"
const MyComponent = React.forwardRef((props = {}, ref: Ref<HTMLDivElement>): JSX.Element => {
return (
<div ref={ref}>
Fun stuff
</div>
);
});
如果我像这样为我的道具声明一个空接口:
interface myProps {}
然后我得到An empty interface is equivalent to '{}',但是当我尝试仅使用{} 声明并且没有实际接口时,我得到:
Don't use `{}` as a type. `{}` actually means "any non-nullish value".
- If you want a type meaning "any object", you probably want `Record<string, unknown>` instead.
- If you want a type meaning "any value", you probably want `unknown` instead.
有什么方法可以为这些 props 声明一个接口/类型,它需要一个空对象并且不会导致我出现 linting 问题?
更新:当我按照此问题线程的建议使用空对象类型时,会导致使用组件的位置出现类型错误。
Type '{ ref: RefObject<HTMLDivElement>; }' is not assignable to type 'Pick<NoElements<Record<string, never>>, string>'.
Property 'ref' is incompatible with index signature.
Type 'RefObject<HTMLDivElement>' is not assignable to type 'never'.
显示在:
<MyComponent ref={refToForward} />
似乎有鸡蛋的情况。
【问题讨论】:
-
如果您改用
React.forwardRef<HTMLDivElement, any>()会怎样?
标签: reactjs typescript eslint tslint