如何在 React 中使用 RXJS fromEvent? [英] How do I use RXJS fromEvent in React?
问题描述
我正在尝试在反应中记录按钮上的点击事件:
I'm trying to log the click event on a button in react:
const InputBox = () => {
const clicky = fromEvent(
document.getElementById('clickMe'),
'click'
).subscribe(clickety => console.log({ clickety }));
return (
<button id="clickMe" type="button">
Click Me
</button>
);
};
我收到以下错误无效的事件目标"
I get the following error 'Invalid event target'
设置似乎没问题.如果我用 document
替换 document.getElementById('clickMe')
然后它会记录点击次数.但这会记录文档中的任何点击,而我只想点击相关按钮.
The setup seems to be fine. If I replace document.getElementById('clickMe')
with document
then it logs the clicks. But that logs any click in the document and I just want the clicks on the button in question.
我尝试使用 ref 代替...
I tried using a ref instead...
const InputBox = () => {
const buttonEl = React.useRef(null);
const clicky = fromEvent(buttonEl.current, 'click').subscribe(clickety =>
console.log({ clickety })
);
return (
<button ref={buttonEl} type="button">
Click Me
</button>
);
};
...但随后我收到了相同的无效事件目标"错误.
...but then I get the same 'Invalid event target' error.
谁能帮我理解为什么这是一个无效的事件目标以及如何解决这个问题,以便我可以在反应中使用 fromEvent.
Can someone help me understand why this is an invalid event target and how to fix this so that I can use fromEvent in react.
更新
问题是我在安装 react 组件时没有注册 observable.
The problem was that I did not register the observable when mounting the react components.
如果这样做,则卸载时还必须卸载组件.
If you do this, you must also unmount the component when unmount.
这现在对我有用.
const InputBox = () => {
React.useEffect(() => {
const click$ = fromEvent(
document.getElementById('clickMe'),
'click'
).subscribe(clickety => console.log({ clickety }));
return () => click$.unsubscribe();
}, []);
return (
<button id="clickMe" type="button">
Click Me
</button>
);
};
推荐答案
将它包裹在 useEffect()
中,这就是 dom 准备好的时候
Wrap it in useEffect()
that's when the dom is ready
const InputBox = () => {
const buttonEl = React.useRef(null);
useEffect(() => {
const clicky = fromEvent(buttonEl.current, 'click').subscribe(clickety =>
console.log({ clickety })
);
return () => clicky.unsubscribe();
}, []);
return (
<button ref={buttonEl} type="button">
Click Me
</button>
);
};
这篇关于如何在 React 中使用 RXJS fromEvent?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!