React.js throttle mousemove event keep throwing event.persist() error

前端 未结 2 1458
青春惊慌失措
青春惊慌失措 2021-02-01 23:53

I need to throttle the mousemove event, and I follow the tips below to build the method, but doesn\'t work: Perform debounce in React.js

Here is my code (http://jsbin.co

相关标签:
2条回答
  • 2021-02-02 00:13

    With hooks:

    const Tool = () => {
      const onMouseMove = useMemo(() => {
        const throttled = _.throttle(e => console.log(e.screenX), 300);
        return e => {
          e.persist();
          return throttled(e);
        };
      }, []);
      return (
        <div className="tool">
          <div className="tool__body" onMouseMove={onMouseMove}>
            Content
          </div>
        </div>
      );
    };
    
    0 讨论(0)
  • 2021-02-02 00:29

    e.persist needs to be called synchronously with the event, the handler can be called asynchronously. Here is a fix:

    class Tool extends React.Component {
      constructor(props) {
        super(props);
        this._throttledMouseMove = _.throttle(this._throttledMouseMove.bind(this), 2000);
      }
    
      _throttledMouseMove = (e) => {
        console.log(e.screenX);
      }
    
      render() {    
        return (
          <div ref="tool" className="tool">
            <div ref="toolBody"
                 className="tool__body"
                 onMouseMove={this._onMouseMove}>
            </div>
          </div>
        )
      }
    
      _onMouseMove = (e) => {
        e.persist();
        this._throttledMouseMove(e);
    
      }
    }
    ReactDOM.render(<Tool/>, document.querySelector('.main'))
    

    The relevant change is calling _onMouseMove directly from the event, and setting up a second method to actually handle event that's been throttled.

    0 讨论(0)
提交回复
热议问题