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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...