令我惊讶的是,以下代码,意味着在我的React Component类中限制mousemove
并不按预期工作,状态始终报告为true& mousemove继续被连续发射。我不明白为什么会这样。
class SVGParent extends React.Component {
constructor(){
super( props );
...
this.dispatchMouseMoveThrottle = this.dispatchMouseMoveThrottle.bind( this );
}
...
dispatchMouseMoveThrottle( a ){
let state = true;
let dispatchMouseMove = this.props.dispatchMouseMove;
return( function( e ){
e.persist(); // this excludes from React's synthetic event system
setTimeout( function(){
state = true;
}, 5000);
if( state === true ){
state = false;
return( dispatchMouseMove( abc ));
}
});
}
render(){
...
return(
<svg
...
mousemove = {this.dispatchMouseMoveThrottle( a )}
</svg>
);
}
答案 0 :(得分:1)
我认为,问题是当mousemove
事件触发时,它不会调用dispatchMouseMoveThrottle(a)
返回的函数。相反,它每次触发时都会调用dispatchMouseMoveThrottle(a)
。这就是为什么state
变量总是true
。
我认为您最好将state
变量保留为组件中的全局变量。或者您可以尝试使用lodash
debounce
或throttle
方法,这可能会有所帮助。
答案 1 :(得分:0)
我通过在模块和模块中声明global
变量来解决它。然后在组件内读取/修改它。
代码:
let mouseMoveState = true;
const changeMouseMoveState = function( changeTo ){
mouseMoveState = changeTo;
};
class SVGParent extends React.Component{
...
dispatchMouseMoveThrottle( a, b ){
let dispatchMouseMove = this.props.dispatchMouseMove;
return( function( e ){
if( a.mouseDownState === true ){
e.persist(); // this excludes from React's synthetic event system
if( mouseMoveState === true ){
setTimeout( function(){
changeMouseMoveState( true );
}, 500 );
changeMouseMoveState( false );
return( dispatchMouseMove( a, b ));
}
}
});
}