react-google-recaptcha "ref" React 打字稿中的类型错误

react-google-recaptcha "ref" type error in React typescript

我正在尝试在类型脚本项目

中实现来自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

根据他们的文档:Invisible reCAPTCHA 您只需要正确输入 recaptcha Ref 即可避免可能出现的 Typescript 错误。

如果您不使用 executeAsync 方法,您可以使用 React.createRef(自 React 16.3 起)并以这种方式输入您的 recaptcha ref:

import ReCAPTCHA from "react-google-recaptcha";

const recaptchaRef = React.createRef<ReCAPTCHA>()
 
ReactDOM.render(
  <form onSubmit={() => { recaptchaRef.current.execute(); }}>
    <ReCAPTCHA
      ref={recaptchaRef}
      size="invisible"
      sitekey="Your client site key"
      onChange={onChange}
    />
  </form>,
  document.body
);

此外,您可以使用 executeAsync 方法来使用基于承诺的方法。然后你可以通过这种方式避免 Typescript 错误:

import ReCAPTCHA from "react-google-recaptcha";
 
 
const ReCAPTCHAForm = (props) => {
  const recaptchaRef = React.useRef<ReCAPTCHA>();
 
  const onSubmitWithReCAPTCHA = async () => {
    const token = await recaptchaRef?.current?.executeAsync();
 
    // apply to form data
  }
 
  return (
    <form onSubmit={onSubmitWithReCAPTCHA}>
      <ReCAPTCHA
        ref={recaptchaRef as React.RefObject<ReCAPTCHA>}
        size="invisible"
        sitekey="Your client site key"
      />
    </form>
  )
 
}