How do I use RXJS fromEvent in React?

后端 未结 2 663
故里飘歌
故里飘歌 2021-01-14 23:34

I\'m trying to log the click event on a button in react:

const InputBox = () => {
  const clicky = fromEvent(
    document.getElementById(\'clickMe\'),
           


        
相关标签:
2条回答
  • 2021-01-15 00:07

    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

    0 讨论(0)
  • 2021-01-15 00:20

    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>
      );
    };
    
    0 讨论(0)
提交回复
热议问题