reactjs - 使用React.fowardRef和useImperativeHandle时如何创建ref的JSDoc?

标签 reactjs react-hooks jsdoc react-ref

我没有在我的reactjs项目中使用Typescript,但是我仍然想用JSDocs记录我的组件。
问题出在哪里,我有一个带有React.forwardRef的功能组件,并且我想创建一个JSDoc到引用,因为我正在使用useImperativeHandle并将不同的值传递给引用。
可以使用JSDoc记录ref来显示我在useImperativeHandle中传递的方法和属性?如果是,怎么办?
我想要的例子在哪里
在一个组件中,我将React.fowardRefuseImperativeHandle一起使用

export const Foo = React.fowardRef((props, ref) => {

    useImperativeHandle(ref, () => ({
        myMethod,
        // other methods and properties
    }))

    return <div>{/* ... */}</div>
}
当将reffooRef.current一起用于该组件时,我想在键入myMethod或按. + Ctrl时查看Space或其他属性。

最佳答案

虽然我不知道这是否是完美的解决方案,但对我有用的是简单地为所有 Prop (包括ref)编写一个typedef,然后将其传递给JSDoc中的@type属性。
这是一个应该起作用的代码段:

import React from 'react';
import PropTypes from 'prop-types';

/**
 * @typedef {Object} RefType
 * @property {Object} current
 * @property {() => void} current.methodOne
 * @property {() => void} current.methodTwo
 */

/**
 * @typedef {Object} Props
 * @property {RefType} ref
 * @property {string} value
 * @property {((event: React.ChangeEvent<HTMLInputElement>) => void) | undefined} onChange
 */

/**
 * @type {React.FC<Props>}
 */
export const Input = React.forwardRef((
  props, 
  /** @type {RefType} */
  ref) => {
  return <input ref={ref} onChange={props.onChange} value={props.value} />
})

Input.propTypes = {
  value: PropTypes.string.isRequired,
  onChange: PropTypes.func.isRequired,
};

Input.displayName = 'Input';
因此,当我随后使用该组件时,例如,这是我在VSCode中获得的智能感知:
Intellisense after using said component.
智能感知应该在整个项目中起作用。
编辑:我应该解释为什么我包括PropTypes。我遇到了与您同样的问题,并找到了解决方案,但我还需要开发工具来保留组件名称。开发人员工具会显示React.forwardRef而不是实际的组件名称。 displayName属性将完成保留原始名称的技巧。
编辑:如果您需要在组件本身内部具有自动完成功能,则可以像下面的图像链接那样进行。我已经更新了代码片段以反射(reflect)这一点。
Autocomplete on ref argument itself.

关于reactjs - 使用React.fowardRef和useImperativeHandle时如何创建ref的JSDoc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63196529/

相关文章:

reactjs - 使用 Ethersjs 获取 ETH 余额

css - Material UI,左侧为 Appbar Logo ,中间为 Tabs

javascript - 获取 JSON 格式的 JSDoc 输出

javascript - setState 较晚更新组件一状态

javascript - undefined 不是函数(计算 '_this._registerEvents()' )

javascript - 在 React Hook 中从 firebase promise 获取值(value)

javascript - 在 React 中,当我触发另一个组件中的 Add 函数时,如何正确使用钩子(Hook)来更新一个组件?

javascript - React Hooks 只能在函数组件内部调用

javascript - 如何用ngdocs描述一个提供函数集合的返回对象?

documentation - VSCode : How to document promise that resolves with complex object?