gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:48:18 24 4
gpt4 key购买 nike

我没有在我的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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com