- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我没有在我的reactjs项目中使用Typescript,但是我仍然想用JSDocs记录我的组件。
问题出在哪里,我有一个带有React.forwardRef
的功能组件,并且我想创建一个JSDoc到引用,因为我正在使用useImperativeHandle
并将不同的值传递给引用。
可以使用JSDoc记录ref
来显示我在useImperativeHandle
中传递的方法和属性?如果是,怎么办?
我想要的例子在哪里
在一个组件中,我将React.fowardRef
与useImperativeHandle
一起使用
export const Foo = React.fowardRef((props, ref) => {
useImperativeHandle(ref, () => ({
myMethod,
// other methods and properties
}))
return <div>{/* ... */}</div>
}
当将
ref
与
fooRef.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中获得的智能感知:
React.forwardRef
而不是实际的组件名称。
displayName
属性将完成保留原始名称的技巧。
关于reactjs - 使用React.fowardRef和useImperativeHandle时如何创建ref的JSDoc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63196529/
我有一个带有保存按钮的组件 requestSaveAsync()}>Save 我还需要能够从应用程序的顶层调用 requestSaveAsync,因此我在名为 useEditRow 的自定义钩子(H
我在子组件的 useImperativeHandle Hook 中创建了一个方法。然后,我可以完美地从父组件访问它。就像下面的例子。但是,我无法从子组件访问它。换句话说,focus from pare
我在子组件的 useImperativeHandle Hook 中创建了一个方法。然后,我可以完美地从父组件访问它。就像下面的例子。但是,我无法从子组件访问它。换句话说,focus from pare
function App(){ const cntEl:any = React.useRef(null); // I don't know what type should be here.
我需要使用 ref获取孙组件的状态,我使用 useImperativeHandle 对其进行了自定义,简化了整个代码 here . function App() { const ref = use
我不明白为什么需要以下 useImperativeHandle、useLayoutEffect 和 useDebugValue 钩子(Hook),您能否举例说明何时可以使用它们,但请不要使用文档中的示
我需要访问子组件的位置。据我了解,要访问子属性,我需要使用 useImperativeHandle 将子 API 添加到其 ref。此外,我需要使用 forwardRef 将引用从父级传递给子级。所以
文档中提供的示例如下: function FancyInput(props, ref) { const inputRef = useRef(); useImperativeHandle(ref
我是一名优秀的程序员,十分优秀!