首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Typescript react:类型推断不适用于回调引用

Typescript react:类型推断不适用于回调引用
EN

Stack Overflow用户
提问于 2020-08-07 17:23:29
回答 1查看 527关注 0票数 1

我的react组件只需要一个回调ref。我使用useState作为回调引用。

代码语言:javascript
运行
复制
const [refElement, setReference] = useState(null); 

在渲染内部:

代码语言:javascript
运行
复制
<div
// this ref is throwing ts error
   ref={setArrowElement}
   style={styles.arrow}
   id="arrow"
/>

Typescript错误:在tsc

代码语言:javascript
运行
复制
- 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.
EN

回答 1

Stack Overflow用户

发布于 2021-04-29 02:50:34

您可以通过键入useState函数来修复此问题:

代码语言:javascript
运行
复制
const [refElement, setReference] = useState<HTMLDivElement | null>(null);

...

<div ref={setReference} />
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63298903

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档