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

问题描述 投票:0回答:3

我正在尝试将引用转发到不带任何道具的 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>
  );
});

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

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.

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

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

reactjs typescript eslint tslint
3个回答
4
投票

如果你想使用

forwardRef
但不需要道具,你可以试试这个:

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

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>
  );
});

0
投票

对我来说,由于

https://eslint.org/docs/latest/rules/no-unused-vars#args-after-used 的 lint 规则 
ref
 参数,使用 
after-used 后它会使用下划线 粗略地指出,如果使用下一个参数,则不会检查前一个参数。我知道这个问题有点晚了,但希望这个答案对某人有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.