簡體   English   中英

React typescript 中的 react-google-recaptcha“ref”類型錯誤

[英]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

IE

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 方法來使用基於 promise 的方法。 然后你可以通過這種方式避免 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>
  )
 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM