我没有在我的reactjs项目中使用typescript,但我仍然想用JSDocs来记录我的组件。
问题是我有一个带有React.forwardRef
的函数组件,我想创建一个指向ref的JSDoc,因为我使用useImperativeHandle
并将不同的值传递给ref。
是否可以使用JSDoc来记录ref
,以显示我在useImperativeHandle
中传递的方法和属性?如果是,是如何实现的?
Where是我想要的示例
在一个组件中,我使用了带有useImperativeHandle
的React.fowardRef
export const Foo = React.fowardRef((props, ref) => {
useImperativeHandle(ref, () => ({
myMethod,
// other methods and properties
}))
return <div>{/* ... */}</div>
}
在fooRef.current
中使用该组件的ref
时,我希望在键入.
或按Ctrl
+ Space
时看到myMethod
或其他属性。
发布于 2020-10-05 13:14:03
虽然我不知道这是否是完美的解决方案,但对我来说起作用的只是为所有属性(包括ref)编写一个类型定义,然后将其传递给@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';
因此,当我使用该组件时,下面是我在VSCode中获得的智能感知,例如:Intellisense after using said component.
智能感知应该在整个项目中工作。
编辑:我应该解释一下为什么我要包含PropTypes。我遇到了与您相同的问题,并找到了解决方案,但我也需要开发工具来保留组件名称。开发工具将显示React.forwardRef
而不是真实的组件名称。displayName
属性将完成保留原始名称的工作。
编辑:如果你需要在组件内部自动完成,你可以像下面的图片链接那样做。我已经更新了代码片段以反映这一点。Autocomplete on ref argument itself.
https://stackoverflow.com/questions/63196529
复制