我有一个类似这样定义的keydown处理函数:
handleOnKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>) => {
if (key.isEscape(e.key)) {
stopEvent(e);
this.props.handleClose(e);
}
}
然而,在我的代码的另一部分中,该函数被传递给removeEventListener
和addEventListener
:
componentDidMount () {
const { current: modal } = this.modalRef;
if (modal) {
modal.addEventListener('keydown', this.handleOnKeyDown);
}
}
componentWillUnmount () {
const { current: modal } = this.modalRef;
if (modal) {
modal.removeEventListener('keydown', this.handleOnKeyDown);
}
}
我遇到以下 TypeScript 错误:
No overload matches this call.
Overload 1 of 2, '(type: "keydown", listener: (this: HTMLDivElement, ev: KeyboardEvent) => any, options?: boolean | EventListenerOptions | undefined): void', gave the following error.
Argument of type '(e: React.KeyboardEvent<HTMLButtonElement>) => void' is not assignable to parameter of type '(this: HTMLDivElement, ev: KeyboardEvent) => any'.
Types of parameters 'e' and 'ev' are incompatible.
Type 'KeyboardEvent' is missing the following properties from type 'KeyboardEvent<HTMLButtonElement>': locale, nativeEvent, isDefaultPrevented, isPropagationStopped, persist
Overload 2 of 2, '(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions | undefined): void', gave the following error.
Argument of type '(e: React.KeyboardEvent<HTMLButtonElement>) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
Type '(e: React.KeyboardEvent<HTMLButtonElement>) => void' is not assignable to type 'EventListener'.
Types of parameters 'e' and 'evt' are incompatible.
Type 'Event' is missing the following properties from type 'KeyboardEvent<HTMLButtonElement>': altKey, charCode, ctrlKey, getModifierState, and 12 more.ts(2769)
有什么解决方法?
类型为'(e: React.KeyboardEvent<HTMLButtonElement>) => void'的参数无法分配给类型为'(this: HTMLDivElement, ev: KeyboardEvent) => any'的参数。
- Jaromanda X