我如何在React中使用RXJS fromEvent? [英] How do I use RXJS fromEvent in React?
问题描述
我正在尝试将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.getElementById('clickMe')
替换为 document
,则会记录点击次数.但这会记录文档中的所有点击,而我只想单击相关按钮上的点击.
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.
有人可以帮助我了解为什么这是无效的事件目标以及如何解决此问题,以便可以在react中使用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组件时没有注册可观察对象.
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>
);
};
推荐答案
将其包装在dom准备就绪的 useEffect()
中
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屋!