问题描述
我正在尝试在类型脚本项目中实现来自 react-google-recaptcha 的隐形 reCaptcha
我添加了包的类型
yarn add @types/react-google-recaptcha
<ReCAPTCHA
ref={recaptchaRef} // IN HERE
size="invisible"
sitekey="Your client site key"
/>
Type 'MutableRefObject<undefined>' is not assignable to type 'LegacyRef<ReCAPTCHA> | undefined'.''
Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<ReCAPTCHA>'.
Types of property 'current' are incompatible.
解决方法
只需给它一个初始值 null
。在您当前的实现中,它采用 undefined
作为初始值。
const recaptchaRef = useRef(null)
// or
const recaptchaRef = useRef<ReCAPTCHA>(null);
// ....
<ReCAPTCHA
ref={recaptchaRef}
size="invisible"
sitekey="Your client site key"
/>
说明:
通过查看类型,ref
属性需要如下类型:
(JSX attribute) React.ClassAttributes<ReCAPTCHA>.ref?: string | ((instance: ReCAPTCHA | null) => void) | React.RefObject<ReCAPTCHA> | null | undefined
即
string | ((instance: ReCAPTCHA | null) => void) | React.RefObject<ReCAPTCHA> | null | undefined
其中 RefObject
是:
interface RefObject<T> {
readonly current: T | null;
}
因此,current
的值应该是某种类型或 null
。