我正在使用TypeScript和React。在我的组件中,它是一个对话框窗口,我想将触发元素(例如按钮)存储为属性。当组件卸载时,我希望将焦点返回到该元素。然而,我收到了一个来自TSLint的错误,我不确定如何解决。
class Dialog extends React.Component<Props, {}> {
...
focusedElementBeforeDialogOpened: HTMLInputElement;
componentDidMount() {
this.focusedElementBeforeDialogOpened = document.activeElement;
...
}
...
}
我在为属性赋值的那一行收到了错误提示:
[ts] Type 'Element' is not assignable to type 'HTMLInputElement'.
Property 'accept' is missing in type 'Element'.
然而,如果我将属性的类型更改为Element
或甚至是HTMLInputElement
,在componentWillUnmount()
中会收到错误信息。
componentWillUnmount() {
...
this.focusedElementBeforeDialogOpened.focus();
}
这个错误是指元素类型没有
focus()
方法。问题:
有没有办法告诉TypeScript
document.activeElement
应该是输入类型?类似于
this.focusedElementBeforeDialogOpened = <HTMLInputElement>document.activeElement;
或者有更好的方法来声明既支持document.activeElement
又支持.focus()
的类型吗?
nativeElement
属性。在activeElement
之后难道没有吗? - user4676340