2

我正在尝试在类型脚本项目中reCaptchareact-google-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.
4

1 回答 1

9

只需给它一个初始值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

IE

string | ((instance: ReCAPTCHA | null) => void) | React.RefObject<ReCAPTCHA> | null | undefined

哪里RefObject是:

interface RefObject<T> {
  readonly current: T | null;
}

因此, 的值current应该是某种类型或null

于 2021-05-04T13:45:49.057 回答