![](/img/trans.png)
[英]How to solve Type Property '' does not exist on type 'IntrinsicAttributes & Function'?
[英]How to solve Property does not exist in type 'never'
我正在使用库 react-google-recaptcha 生成不可见的 ReCaptcha,我收到以下 typescript 错误:
“从不”类型中不存在属性“执行”
这是代码:
const recaptcha = useRef(null);
useEffect(() => {
let token;
if (recaptchaLoaded) {
token = recaptcha.current?.execute();
}
}, [recaptchaLoaded]);
<ReCAPTCHA
ref={recaptcha}
sitekey={SITE_KEY}
/>
我怎样才能键入 the.execute() 以便不再发生此错误? 或者我应该换一种方式吗?
谢谢
您需要通过向 useRef 提供类型参数来告诉useRef
ref 将引用的类型(因为 TypeScript 无法从初始值null
推断它)。 假设您正在使用此npm
package ,您似乎使用了组件的类型:
const recaptcha = useRef<ReCAPTCHA>(null);
// ^^^^^^^^^^^
更多关于这个; 连同 useRef(null) recaptcha const
const recaptcha = useRef<ReCAPTCHA>(null);
// ^^^^^^^^^
在 recaptcha 组件中,添加一个 onChange 事件,如下面的代码片段所示。
<ReCAPTCHA
ref={recaptchaRef}
onChange={handleCaptchaChange}
sitekey="yourSiteKey"
/>
const handleCaptchaChange = () => {
if (recaptchaRef.current) {
const token = recaptchaRef.current.getValue();
if (token)
setSaveButtonDisabled(token.length <= 0);
}
}
请注意上面检查 recaptcha.current (if (recaptchaRef.current)) 并检查 null token (if (token)) 的行
以上将断言可能的 null 错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.