gpt4 book ai didi

reactjs - 如何将 typescript 中的目标设置为rxjs中的fromEvent()

转载 作者:行者123 更新时间:2023-12-02 10:46:05 24 4
gpt4 key购买 nike

我正在使用' 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



enter image description here

我试图根据文档将定义更改为节点列表:

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))

从技术上讲,它可以工作并阻止编译器提示,但是如果我在 localhost 上打开实际网站,我只会收到一堆引用库的错误。

enter image description here

知道我在做什么错吗?

最佳答案

我遇到了同样的问题,你只需要显式强制(或强制转换)类型,所以我为此做了一个小 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com