[英]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.