首页 > 解决方案 > 打字稿反应:类型推断不适用于回调参考

问题描述

我的反应组件只需要一个回调引用。我正在使用 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.

标签: reactjstypescript

解决方案


您可以通过键入useState函数来解决此问题:

const [refElement, setReference] = useState<HTMLDivElement | null>(null);

...

<div ref={setReference} />

推荐阅读