- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用' rxjs
' 库旁边的 typescript 。
问题是,我不知道如何通过 简单的按钮到 fromEvent()
来自 rxjs
尝试这样做会使编译器提示:
import React from 'react';
import * as rx from 'rxjs';
const RXComponent: React.FC = () => {
rx.fromEvent(document.getElementById('dblbutton'), 'click')
return (
<form>
<input type='button' id='dblbutton' value='Click me!'>
</input>
</form>
)
}
export default RXComponent;
Argument of type 'HTMLElement | null' is not assignable to parameter of type 'FromEventTarget'. Type 'null' is not assignable to type 'FromEventTarget'. TS2345
List of DOM Nodes, returned for example by document.querySelectorAll or Node.childNodes.
Although this collection is not event target in itself, fromEvent will iterate over all Nodes it contains and install event handler function in every of them. When returned Observable is unsubscribed, function will be removed from all Nodes.
const btn = document.querySelectorAll('#dblbutton')
const obs = rx.fromEvent(btn, 'click')
obs.subscribe(x => console.log(x))
最佳答案
我遇到了同样的问题,你只需要显式强制(或强制转换)类型,所以我为此做了一个小 helper
import * as Rx from 'rxjs'
import { FromEventTarget } from 'rxjs/internal/observable/fromEvent'
const
mkEventTarget = (qs: string): FromEventTarget<Event> =>
document.querySelector (qs) as FromEventTarget<Event>
, evClicks: Rx.Observable<Event> = Rx.fromEvent (mkEventTarget ("#btn"), "click")
evClicks.subscribe (() => console.log ("Test"))
关于reactjs - 如何将 typescript 中的目标设置为rxjs中的fromEvent(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58172960/
我是一名优秀的程序员,十分优秀!