reactjs - 打字稿反应:类型推断不适用于回调参考
问题描述
我的反应组件只需要一个回调引用。我正在使用 useState 作为回调参考。
const [refElement, setReference] = useState(null);
内部渲染:
<div
// this ref is throwing ts error
ref={setArrowElement}
style={styles.arrow}
id="arrow"
/>
打字稿错误:开tsc
- error TS2322: Type 'Dispatch<SetStateAction<null>>' is not assignable to type 'string | ((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement> | null | undefined'.
Type 'Dispatch<SetStateAction<null>>' is not assignable to type '(instance: HTMLDivElement | null) => void'.
Types of parameters 'value' and 'instance' are incompatible.
Type 'HTMLDivElement | null' is not assignable to type 'SetStateAction<null>'.
Type 'HTMLDivElement' is not assignable to type 'SetStateAction<null>'.
Type 'HTMLDivElement' provides no match for the signature '(prevState: null): null'.
216 ref={setReference}
~~~
../../node_modules/@types/react/index.d.ts:145:9
145 ref?: LegacyRef<T>;
~~~
The expected type comes from property 'ref' which is declared here on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'
Found 1 error.
解决方案
您可以通过键入useState
函数来解决此问题:
const [refElement, setReference] = useState<HTMLDivElement | null>(null);
...
<div ref={setReference} />
推荐阅读
- javascript - 如果我有两个共享域的 iframe,一个上的 postmessage 会触发另一个上的消息事件吗?
- mysql - 如何在云外壳中创建带有外键的表?
- numpy - 为什么卷积运算后输入图像会翻转?
- reactjs - 在 React 中访问 StencilJS 组件资产
- yii2 - Yii2 url 路由管理器规则对多个路径失败
- python - 如何在 python 海龟游戏中按键运行一个类或函数?
- php - 在php中对数组中的一个double值进行分组
- neo4j - 在 Neo4j Cypher 中,$ 符号作为单词的前缀是什么意思
- sql - 在 BigQuery 中使用 COALESCE 时出现无法识别的名称
- css - 从一个 svg 变形到另一个