如何解决React 打字稿中的 react-google-recaptcha“ref”类型错误
我正在尝试在类型脚本项目中实现来自 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
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。