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