How do I use RXJS fromEvent in React?

空扰寡人 提交于 2020-03-03 03:42:44

问题


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'

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.

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.

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.


Update

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.

This works for me now.

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

回答1:


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 (
    <button ref={buttonEl} type="button">
      Click Me
    </button>
  );
};



回答2:


did you try by query selector? like this

const InputBox = () => {
  const clicky = fromEvent(document.querySelector('button'),'click')
     .subscribe(clickety => console.log({ clickety }));

  return (
    <button type="button">
      Click Me
    </button>
  );
};

that's works for me



来源:https://stackoverflow.com/questions/58369735/how-do-i-use-rxjs-fromevent-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!