繁体   English   中英

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

[英]How do i annotate React.forwardRef with jsdoc comments so that intellisense can show up for the underlying component?

我有一个这样写为 function 的 React 组件:

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

Button.propTypes = {
  text: PropTypes.string.isRequired,
  icon: PropTypes.string.isRequired
}

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

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

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

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

这取决于你想对这些类型有多迂腐。 通常,这些组件的使用与其他功能组件几乎相同,因此最简单的方法是将结果的类型声明为功能组件。 props 的技巧是首先为 prop 类型创建一个变量,然后为泛型类型引用该变量(或者至少,我还没有找到一种方法让它在没有间隙值的情况下工作):

/**
 * @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

如果要更准确的话, 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

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

类型的定义在这里: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/3423b4fc3e3da09f8acc386bc2fee6fb8f5e0880/types/react/index.d.ts#L559参考。 但是,由于您实际上并没有静态键入要传入的ref ,因此您可能只是选择用 ? 省略那个?

/**
 * @type React.ForwardRefRenderFunction<?, ButtonPropTypes>
 */

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

/**
 * @type React.FC<UnWrappedButton.propTypes>
 */

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM