在带有 React 和 Typescript 的 div 上使用 onFocus

Use onFocus on a div with React and Typescript

我不知道如何在 React 和 Typescript 中使用 Focus 事件:

private onFocus(event: FocusEvent) {

}

...

<div
  tabIndex={0}
  onFocus={this.onFocus}
>
 Element
</div>

使用上面的代码我得到以下错误

Types of property 'onFocus' are incompatible.

Type '(event: FocusEvent) => void' is not assignable to type '((event: FocusEvent) => void) | undefined'.

Type '(event: FocusEvent) => void' is not assignable to type '(event: FocusEvent) => void'.

Types of parameters 'event' and 'event' are incompatible.

Type 'FocusEvent' is not assignable to type 'FocusEvent'.

Property 'initFocusEvent' is missing in type 'FocusEvent'.

我尝试了很多方法来让 Typescript 编译器满意,但似乎没有任何效果。

根据错误,您似乎使用了错误的 FocusEvent 类型 - 您正在处理 React 合成事件,因此您需要使用 React 类型。

我在使用以下处理程序时没有遇到任何错误(您的结果可能因 react.d.ts 的版本而异):

import {FocusEvent} from 'react'
...
private onFocus(ev: FocusEvent<any>){
    console.log(ev);
}