类型保护 React.KeyboardEvent 以重用事件处理程序

问题描述 投票:0回答:2

我创建了一个类似于 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.

打字保护的好方法是什么?有没有更好的方法来编写函数?

谢谢你。

user-input onkeydown react-typescript
2个回答
1
投票

结果使用交叉类型解决了问题:

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' 属性),请告诉我。 感觉不必要的黑客!


0
投票

React.Events 对象有一个“nativeEvent”属性,用于存储本机事件,您可以检查该属性。

在你的代码中,看起来像

function initSearch(
    e:
      | (React.MouseEvent<HTMLButtonElement>
      | (React.KeyboardEvent<HTMLInputElement>
  ): void {
    if (e.nativeEvent instanceof MouseEvent || e.key === 'Enter') {
      console.log(searchParam);
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.