在没有属性的Typescript中使用React.forwardRef

问题描述

我正在尝试将ref转发到不带任何道具的Typescript组件。当我使用React.forwardRef时,它带有两个参数:props和ref。我的组件不使用道具。如何声明我的组件没有棉绒或编译错误

现在我有

// 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.

是否可以通过某种方式为这些道具声明一个接口/类型,而该接口/类型期望一个空对象并且不会导致我的掉毛问题?

更新:当我根据此问题线程的建议使用空对象类型时,在使用组件的地方会导致类型错误

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} />

好像有个鸡蛋的情况。

解决方法

您可以在props前面加上这样的下划线_props,以摆脱props is declared but its value is never used

对于空接口,我通常使用类型,因此在您的情况下为type myProps = {}

UPD:

我们如何将类型传递到<>中,例如:

type Props = {};

const MyComponent = React.forwardRef<HTMLDivElement,Props>((props,ref) => {
  return (
      <div ref={ref}>
        Fun stuff
      </div>
  );
});