gpt4 book ai didi

javascript - TypeScript:如何无误地访问 onChange 事件数据? (对象可能是 'null' )

转载 作者:行者123 更新时间:2023-11-30 19:27:47 26 4
gpt4 key购买 nike

请看下面这个最小的例子:

/** @jsx h */
import { h, FunctionalComponent } from 'preact';

const Test: FunctionalComponent = () => {
return (
<select
value="1"
onChange={(event) => {
console.log(event.target.value);
}}
>
<option value="1">1</option>
<option value="2">2</option>
</select>
);
};

image showing unsafe access to object field

如何解决显示 Object is possibly 'null' 的错误?

最佳答案

这是一个“TypeScript 安全检查”,通知您 event.target 可能为 null,这将导致访问 event.target.value 时抛出错误在运行时。

可以使用 "non-null assertion operation" 消除此警告/错误:

<select value="1" onChange={(event) => {
/* Add ! after target to state that "event.target!" is defined and
that value field can be safely accessed. This is a non-null
assertion */
console.log(event.target!.value);
}}>

或者在访问之前检查 event.target 是否已定义:

<select value="1" onChange={(event) => {

const { target } = event;
if(target) {
/* The ! is not needed seeing target is dedeuced as being defined */
console.log(target.value);
}
}}>

关于javascript - TypeScript:如何无误地访问 onChange 事件数据? (对象可能是 'null' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56729530/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com