在 Typescript 中使用 React.forwardRef 而不使用 props

Bra*_*ing 6 typescript reactjs eslint tslint

我正在尝试将引用转发到不带任何道具的 Typescript 组件。当我使用React.forwardRef它时,它需要两个参数:props 和 ref。我的组件不使用 props。如何声明我的组件而不出现 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>
  );
});
Run Code Online (Sandbox Code Playgroud)

如果我为我的 props 声明一个空接口,如下所示:

interface myProps {}
Run Code Online (Sandbox Code Playgroud)

然后我得到了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.
Run Code Online (Sandbox Code Playgroud)

有什么方法可以为这些道具声明一个接口/类型,它需要一个空对象并且不会导致我出现 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'.
Run Code Online (Sandbox Code Playgroud)

演出地点:

<MyComponent ref={refToForward} />
Run Code Online (Sandbox Code Playgroud)

看来是有先有鸡还是先有蛋的情况。

小智 5

如果你想使用forwardRef但不需要 props,你可以试试这个:

const MyComponent = forwardRef((_: unknown, ref: Ref<HTMLDivElement>) => {
  return (
      <div ref={ref}>
        ...
      </div>
  );
});
Run Code Online (Sandbox Code Playgroud)


Yes*_*pov 0

您可以props像这样在 前面加上下划线_props来去掉props is declared but its value is never used.

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

更新:

我们将类型传递到 中怎么样<>,例如:

type Props = {};

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