我创建了一个类似于 Google 的 search-bar-React-Component。 如果我单击“搜索”图标或按 Enter 键,它应该根据输入启动搜索。
我想为单击和按键处理程序重用相同的函数:
...
var [searchParam, setSearchParam] = useState('');
function initSearch(
e:
| React.MouseEvent<HTMLButtonElement>
| React.KeyboardEvent<HTMLInputElement>
): void {
if (e.type == 'click' || (e.type == 'keydown' && e.key == 'Enter')) {
console.log(searchParam); /* ⬆️ this throws the error */
}
}
...
TypeScript 不断给我以下错误:
'属性'key'在类型'MouseEvent
我尝试了以下两种方法:
(e instance of KeyboardEvent && e.key == 'Enter') // This is always false, since e is a React.KeyboardEvent
(e instance of React.KeyboardEvent) // KeyboardEvent is not a property of React.
打字保护的好方法是什么?有没有更好的方法来编写函数?
谢谢你。
结果使用交叉类型解决了问题:
function initSearch(
e:
| (React.MouseEvent<HTMLButtonElement> & { type: 'click' }) /*⬅️*/
| (React.KeyboardEvent<HTMLInputElement> & { type: 'keydown' }) /*⬅️*/
): void {
if (e.type == 'click' || (e.type == 'keydown' && e.key == 'Enter')) {
console.log(searchParam);
}
}
我检查了类型定义,结果发现“type”属性仅定义为“string”,而不是明确的原始值。
如果我在这里遗漏了一些东西(即 keydown 事件可能以某种方式不包含 e.type == 'keydown' 属性),请告诉我。 感觉不必要的黑客!
React.Events 对象有一个“nativeEvent”属性,用于存储本机事件,您可以检查该属性。
在你的代码中,看起来像
function initSearch(
e:
| (React.MouseEvent<HTMLButtonElement>
| (React.KeyboardEvent<HTMLInputElement>
): void {
if (e.nativeEvent instanceof MouseEvent || e.key === 'Enter') {
console.log(searchParam);
}
}