【发布时间】:2021-06-01 08:44:29
【问题描述】:
我正在努力解决以下错误:
Argument of type 'ChangeEvent<HTMLInputElement | HTMLTextAreaElement>' is not assignable to parameter of type 'KeyboardEvent<HTMLInputElement>'.
Type 'ChangeEvent<HTMLInputElement | HTMLTextAreaElement>' is missing the following properties from type 'KeyboardEvent<HTMLInputElement>': altKey, charCode, ctrlKey, getModifierState, and 8 more. TS2345
166 | autoComplete="off"
167 | onChange={(event): void => {
> 168 | setSearchInput(checkIfThereIsColon(event, event.target.value));
| ^
169 | }}
170 | onKeyDown={(e: KeyboardEvent<HTMLInputElement>) => {
171 | if (!isUserTyping) {
我有一个正在接受搜索输入的组件:
onChange={(event): void => {
setSearchInput(checkIfThereIsColon(event, event.target.value));
}}
onKeyDown={(e: KeyboardEvent<HTMLInputElement>) => {
if (!isUserTyping) {
setIsUserTyping(true);
}
if (e.key === ':') {
disallowFilteringInSearchBar(e);
}
}}
然后它检查用户是否输入了冒号:
const disallowFilteringInSearchBar = (e: KeyboardEvent, ) => { e.preventDefault(); setIsUserTyping(假); 设置模式警报(真); setFiltersModalOpen(true) };
还检查用户是否从剪贴板粘贴了冒号:
function checkIfThereIsColon(event: KeyboardEvent<HTMLInputElement>, eventTargetValue:string) {
let searchStringStrippedOutColon = eventTargetValue;
if (eventTargetValue.includes(":")) {
searchStringStrippedOutColon = eventTargetValue.replace(/:/g, '<disallowed character>');
disallowFilteringInSearchBar(event);
}
return searchStringStrippedOutColon;
}
如果我使用ts-ignore 忽略 TS 错误,一切正常。
我想我在这里没有使用正确的类型:
event: KeyboardEvent<HTMLInputElement>
任何人都可以建议我做错了什么以及如何解决它?真的是类型不对吗?
我也试过替换:
event: KeyboardEvent<HTMLInputElement>
与
event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
但它也不能解决它
【问题讨论】:
-
更改为
ChangeEvent<HTMLInputElement | HTMLTextAreaElement>应该可以。将checkIfThereIsColon更改为上述错误是什么? -
在 if 函数
disallowFilteringInSearchBar(event);内,它在event下划线并表示:Argument of type 'ChangeEvent<HTMLInputElement | HTMLTextAreaElement>' is not assignable to parameter of type 'KeyboardEvent<HTMLInputElement>'.Type 'ChangeEvent<HTMLInputElement | HTMLTextAreaElement>' is missing the following properties from type 'KeyboardEvent<HTMLInputElement>': altKey, charCode, ctrlKey, getModifierState, and 8 more.
标签: reactjs typescript