Yah*_*var 9 typescript reactjs invisible-recaptcha react-google-recaptcha
我正在尝试在类型脚本项目中reCaptcha从react-google-recaptcha中实现不可见
我添加了包的类型
yarn add @types/react-google-recaptcha
Run Code Online (Sandbox Code Playgroud)
但是当我想实现该组件时,我在这里收到类型脚本错误
<ReCAPTCHA
ref={recaptchaRef} // IN HERE
size="invisible"
sitekey="Your client site key"
/>
Run Code Online (Sandbox Code Playgroud)
这是错误的内容
Run Code Online (Sandbox Code Playgroud)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.
Aje*_*hah 21
只需给它一个初始值即可null。它undefined作为当前实现中的初始值。
const recaptchaRef = useRef(null)
// or
const recaptchaRef = useRef<ReCAPTCHA>(null);
// ....
<ReCAPTCHA
ref={recaptchaRef}
size="invisible"
sitekey="Your client site key"
/>
Run Code Online (Sandbox Code Playgroud)
解释:
通过查看类型,ref属性需要如下类型:
(JSX attribute) React.ClassAttributes<ReCAPTCHA>.ref?: string | ((instance: ReCAPTCHA | null) => void) | React.RefObject<ReCAPTCHA> | null | undefined
Run Code Online (Sandbox Code Playgroud)
IE
string | ((instance: ReCAPTCHA | null) => void) | React.RefObject<ReCAPTCHA> | null | undefined
Run Code Online (Sandbox Code Playgroud)
哪里RefObject:
interface RefObject<T> {
readonly current: T | null;
}
Run Code Online (Sandbox Code Playgroud)
因此, 的值current应该是某种类型 或null。