React.js throttle mousemove event keep throwing event.persist()错误 [英] React.js throttle mousemove event keep throwing event.persist() error
问题描述
我需要调整mousemove事件,并按照以下提示构建方法,但不起作用:
在React.js中执行去抖动
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
这是我的代码( http://jsbin.com/binesofepo/edit?js,console,output ):
class Tool extends Component {
constructor(props) {
super(props);
this._onMouseMove = _.throttle(this._onMouseMove.bind(this), 1000)
}
render() {
return (
<div ref="tool" className="tool">
<div ref="toolBody"
className="tool__body"
onMouseMove={this._onMouseMove}></div>
</div>
)
}
_onMouseMove(e) {
e.persist()
console.log(e.screenX)
}
}
如果你保持mousemove在 tool__body
下,会收到以下警告:
If you keep mousemove on the tool__body
, It'll get lots of below warning:
警告:出于性能原因,此合成事件被重用。如果您看到这一点,您将在已发布/无效的综合事件上访问属性
screenX
。这被设置为null。如果您必须保留原始合成事件,请使用event.persist()。请参阅fb.me/react-event-pooling了解更多信息。
Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property
screenX
on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist(). See fb.me/react-event-pooling for more information.
我的反应版本:15.0.2
my react version: "15.0.2"
似乎 e.persist()
不能正常工作。任何想法? :D
Seems e.persist()
doesn't work well. Any idea? :D
推荐答案
e.persist需要与事件同步调用,处理程序可以异步调用。这是一个修复:
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'))
相关更改直接从事件调用_onMouseMove,并设置第二种方法来实际处理已被限制的事件。
The relevant change is calling _onMouseMove directly from the event, and setting up a second method to actually handle event that's been throttled.
这篇关于React.js throttle mousemove event keep throwing event.persist()错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!