我的react组件仅需要一个回调引用。 我将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.
答案 0 :(得分:1)
您可以通过输入 useState
函数来解决此问题:
const [refElement, setReference] = useState<HTMLDivElement | null>(null);
...
<div ref={setReference} />