Javascript 在打字稿中触发点击 - 类型“元素”上不存在属性“点击”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46204003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trigger click in Typescript - Property 'click' does not exist on type 'Element'
提问by Floris
I would like to trigger a click event on a HTML element in Typescript/Reactjs.
我想在 Typescript/Reactjs 中的 HTML 元素上触发点击事件。
let element: Element = document.getElementsByClassName('btn')[0];
element.click();
The code above does work. But I'm getting a Typescript error:
上面的代码确实有效。但我收到打字稿错误:
ERROR in [at-loader] ./src/App.tsx:124:17
TS2339: Property 'click' does not exist on type 'Element'.
So what would be the correct way to do this?
那么这样做的正确方法是什么?
回答by Suren Srapyan
Use the type HTMLElementinstead of Element. HTMLElement inherits from Element. And in the documentation you can find that clickfunction is defined in the HTMLElement.
使用类型HTMLElement而不是Element。HTMLElement 继承自 Element。在文档中,您可以发现该click函数是在 HTMLElement 中定义的。
Cast your element into the HTMLElement via
通过以下方式将您的元素投射到 HTMLElement 中
let element: HTMLElement = document.getElementsByClassName('btn')[0] as HTMLElement;
element.click();
回答by Ved
You should use refto access DOM.
您应该使用ref来访问 DOM。
<button ref={button => this.buttonElement = button} />
In your event handler:
this.buttonElement.click();// trigger click event
Or,Create HtmlEvents and attach to dom element.
或者,创建 HtmlEvents 并附加到 dom 元素。
var event = document.createEvent("HTMLEvents");
event.initEvent("click", true, true);
var button = document.getElementsByClassName('btn')[0];
button.dispatchEvent(event);
回答by Mukesh
Use Like this
像这样使用
(<HTMLElement>document.getElementsByClassName('btn')[0]).click()
回答by Army-U
document
.querySelectorAll<HTMLElement>('.ant-table-row-expand-icon')
.forEach(node => node.click())
回答by fo_
Correct (type safe) way is:
正确(类型安全)方式是:
if (element instanceof HTMLElement) {
element.click();
}
You shouldn't use forced casts (as suggested by other answers) unless you reallyneed them.
除非您真的需要它们,否则您不应该使用强制转换(如其他答案所建议的那样)。

