如何使用 jsdoc 注释注释 React.forwardRef 以便智能感知可以显示给底层组件?

gau*_*430 7 javascript typescript reactjs visual-studio-code

我有一个以函数形式编写的 React 组件,如下所示:

function Button({ text, icon }) {
  return ...
}

Button.propTypes = {
  text: PropTypes.string.isRequired,
  icon: PropTypes.string.isRequired
}
Run Code Online (Sandbox Code Playgroud)

使用此组件时,我在 vscode 中获得自动完成/智能感知

如果我将此组件包装在 React.forwardRef 中, export default React.forwardRef((props, ref) => <Button btnRef={ref} {...props} />)

然后我得到了该forwardRef函数的智能感知,这对我的使用没有帮助,因为现在我无法让道具自动完成/显示在智能感知中。

我尝试React.forwardRef使用 jsdoc extends/进行注释augments,但没有成功,在这种情况下,即使forwardRef使用的默认智能感知也会停止显示。(我相信这是因为 vscode 比 jsdoc 注释更倾向于可用类型)。有没有办法让我获得与未包装组件类似的包装组件的智能感知?这符合我对以与未包装组件类似的方式使用包装组件的理解。

eri*_*2k8 7

这取决于你想对类型有多么迂腐。一般来说,这些组件的使用与其他功能组件几乎相同,因此最简单的方法就是将结果的类型声明为功能组件。道具的技巧是首先为道具类型创建一个变量,并引用泛型类型的变量(或者至少,我还没有找到一种方法让它在没有插页式值的情况下工作):

/**
 * @type React.FC<ButtonPropTypes>
 */
const Button = forwardRef(({ text, icon }, ref) => (
  <button ref={ref}>{text}{icon}</button>
))

const ButtonPropTypes = {
  text: string.isRequired,
  icon: string.isRequired,
  // `ref` isn't a "real" prop, so `prop-types` will not not actually validate
  // this one, but this adds it to the intellisense list if desired. Feel
  // free to just omit it.
  ref: oneOf(shape({ current: any }), func),
}

Button.propTypes = ButtonPropTypes
Run Code Online (Sandbox Code Playgroud)

如果你想更准确的话,它的返回类型forwardRef实际上是:

/**
 * @type React.ForwardRefRenderFunction<HTMLButtonElement, ButtonPropTypes>
 */
const Button = forwardRef(({ text, icon }, ref) => (
  <button ref={ref}>{text}{icon}</button>
))

const ButtonPropTypes = {
  text: string.isRequired,
  icon: string.isRequired,
}

Button.propTypes = ButtonPropTypes
Run Code Online (Sandbox Code Playgroud)

然而,IntelliSense 似乎无法识别该ref道具(工作正常,只是不在列表中)。

类型的定义如下: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/3423b4fc3e3da09f8acc386bc2fee6fb8f5e0880/types/react/index.d.ts#L559 第一个参数是将分配给的值的预期类型参考号 然而,由于您实际上并没有静态地输入ref您要传​​入的内容,因此您可能只是选择使用以下命令省略该内容?

/**
 * @type React.ForwardRefRenderFunction<?, ButtonPropTypes>
 */
Run Code Online (Sandbox Code Playgroud)

认为你对最后一部分的意思是你不会同时拥有未包装和包装的版本。这是典型的模式,因为保留两者并没有真正的用处。但是,顺便说一句,您可以直接引用propTypes任何其他组件的值以用作泛型类型,例如:

/**
 * @type React.FC<UnWrappedButton.propTypes>
 */
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你,埃里希!我这样使用它:`@type React.ForwardRefRenderFunction&lt;React.FunctionComponent, ButtonPropTypes&gt;`,它的工作方式就像一个魅力。 (3认同)