我的react组件只需要一个回调ref。我使用useState作为回调引用。
const [refElement, setReference] = useState(null); 在渲染内部:
<div
// this ref is throwing ts error
ref={setArrowElement}
style={styles.arrow}
id="arrow"
/>Typescript错误:在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.发布于 2021-04-29 02:50:34
您可以通过键入useState函数来修复此问题:
const [refElement, setReference] = useState<HTMLDivElement | null>(null);
...
<div ref={setReference} />https://stackoverflow.com/questions/63298903
复制相似问题