reactjs - Typescript/React useRef 错误:(属性)React.RefObject.current: HTMLFormElement | 空对象可能是“空”.ts(2531)
问题描述
我遇到了 Typescript 的问题,它给了我下面列出的以下错误。的部分const formRef = useRef<HTMLFormElement>(null);
似乎很好,但问题似乎与formRef.current.checkValidity()
.
如何添加打字稿打字/摆脱错误?
错误:
(property) React.RefObject<HTMLFormElement>.current: HTMLFormElement | null
Object is possibly 'null'.ts(2531)
代码:
// React Hooks: Refs
const formRef = useRef<HTMLFormElement>(null);
// Send Verification Code
const sendVerificationCode = (event: any) => {
// Event: Cancels Event (Stops HTML Default Form Submit)
event.preventDefault();
// Event: Prevents Event Bubbling To Parent Elements
event.stopPropagation();
// const reference = <HTMLFormElement>formRef.current;
console.log('WHY IS THE FORM VALID???');
console.log(formRef.current.checkValidity());
// Check Form Validity
if (formRef.current.checkValidity() === true) {
// Validate Form
setValidated(true);
// Redux: Send Verification Code Request
dispatch(sendVerificationCodeRequest(email));
}
else {
// Do Nothing (Form.Control.Feedback Will Appear)
console.log('DO NOTHING');
}
};
解决方案
正如错误所说,问题在于 ref 可能是null
- 事实上,这就是您将其初始化的内容。那意味着formRef.current
可能null
。这意味着formRef.current.checkValidity()
需要检查是否formRef.current
为null
.
您可以使用&&
:
if (formRef.current && formRef.current.checkValidity()) {
// ^^^^^^^^^^^^^^^^^^^
或新的可选链接运算符:
if (formRef.current?.checkValidity()) {
// ^
旁注:几乎没有任何理由=== true
or === false
,当然也没有。checkValidity
返回一个布尔值,所以你已经有一个布尔值可以用if
.
// Idiomatically:
if (x) { // Is this true?
// ...
}
if (!x) { // Is this false?
// ...
}
¹“几乎” - 唯一真正有意义的是,如果您正在测试的内容可能根本不是布尔值,并且您希望检查结果false
是否不是,这是一种罕见的边缘情况。
推荐阅读
- svelte - Svelte:每次更改绑定属性时,如何阻止 {#await} 块刷新?
- reactjs - 即使状态更新,React useState 也会呈现初始值
- oracle11g - Toad:在没有绑定变量弹出窗口的情况下运行 plsql 查询?
- jquery - 从 html 表中的元素获取值
- keras - Keras Loss:允许多个 y_true 值正确
- c# - C# 从串口读取数据 - 如何只获取新的/当前数据?
- sql - 命名动态列 plsql plsql (pivot)
- java - 不显示按钮上的 Java 文本
- ionic-framework - 重新打开浏览器后,ionic 3 storage clear
- android - 如何通过 adb wifi 连接安装应用程序?