【发布时间】:2020-01-29 15:15:02
【问题描述】:
React 的useRef 类型实现不允许我使用联合类型有什么原因吗?
我在 TS 方面不是很有经验,因此无法完全理解错误的原因和底层类型。
function Test() {
const ref = React.useRef<HTMLInputElement | HTMLButtonElement>(null);
return Math.random()
? <input ref={ref} />
: <button ref={ref}></button>;
}
错误:
Type 'RefObject<HTMLInputElement | HTMLButtonElement>' is not assignable to type 'string | ((instance: HTMLButtonElement | null) => void) | RefObject<HTMLButtonElement> | null | undefined'.
Type 'RefObject<HTMLInputElement | HTMLButtonElement>' is not assignable to type 'RefObject<HTMLButtonElement>'.
Type 'HTMLInputElement | HTMLButtonElement' is not assignable to type 'HTMLButtonElement'.
Type 'HTMLInputElement' is not assignable to type 'HTMLButtonElement'.
Types of property 'labels' are incompatible.
Type 'NodeListOf<HTMLLabelElement> | null' is not assignable to type 'NodeListOf<HTMLLabelElement>'.
Type 'null' is not assignable to type 'NodeListOf<HTMLLabelElement>'. TS2322
React 的类型(这样你就不需要查找它们):
interface ClassAttributes<T> extends Attributes {
ref?: LegacyRef<T>;
}
type Ref<T> = { bivarianceHack(instance: T | null): void }["bivarianceHack"] | RefObject<T> | null;
type LegacyRef<T> = string | Ref<T>;
function useRef<T>(initialValue: T|null): RefObject<T>;
interface RefObject<T> {
readonly current: T | null;
}
【问题讨论】:
标签: reactjs typescript react-hooks