【发布时间】:2018-04-22 05:47:34
【问题描述】:
我正在使用 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()的类型?
【问题讨论】:
-
我对 React 不熟悉,但在 Angular 中,你有
nativeElement属性。 `activeElement` 后面没有吗?
标签: javascript reactjs typescript types