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

前端 未结 2 1457
青春惊慌失措
青春惊慌失措 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: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 (
          
    ) } _onMouseMove = (e) => { e.persist(); this._throttledMouseMove(e); } } ReactDOM.render(, 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.

提交回复
热议问题