Ven*_*sky 5 jsdoc reactjs react-ref react-hooks
我没有在 reactjs 项目中使用 typescript,但我仍然想用 JSDocs 记录我的组件。
问题是我有一个功能组件,React.forwardRef我想为 ref 创建一个 JSDoc,因为我正在使用useImperativeHandle不同的值并将不同的值传递给 ref。
可以记录ref使用 JSDoc 来显示我传入的方法和属性useImperativeHandle吗?如果是,如何?
我想要的例子在哪里
在组件我用React.fowardRef用useImperativeHandle
export const Foo = React.fowardRef((props, ref) => {
useImperativeHandle(ref, () => ({
myMethod,
// other methods and properties
}))
return <div>{/* ... */}</div>
}
Run Code Online (Sandbox Code Playgroud)
当ref将该组件与 一起使用时fooRef.current,我想myMethod在键入.或按Ctrl+时查看或 其他属性Space。
虽然我不知道这是否是完美的解决方案,但对我有用的只是为所有道具(包括 ref)编写一个 typedef,然后将其传递给 @type 属性,所有这些都在 JSDoc 中。这是一个应该有效的片段:
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';
Run Code Online (Sandbox Code Playgroud)
因此,当我然后使用该组件时,这是我在 VSCode 中获得的智能感知,例如: 使用所述组件后的智能感知。
智能感知应该在整个项目中工作。
编辑:我应该解释为什么我包含 PropTypes。我遇到了与您相同的问题,并找到了解决方案,但我还需要开发工具来保留组件名称。开发工具将改为显示React.forwardRef而不是真实的组件名称。该displayName属性将起到保留原始名称的作用。
编辑:如果您需要在组件本身内部自动完成,您可以像下面的图片链接一样完成。我已经更新了代码片段以反映这一点。 在 ref 参数本身上自动完成。
| 归档时间: |
|
| 查看次数: |
954 次 |
| 最近记录: |