在React

时间:2017-09-10 20:16:57

标签: javascript reactjs events dom mouseevent

我正在寻找在事件onmousemoveonmouseup和{{1}期间根据某些任意DOM元素检索鼠标的X和Y坐标的最可靠方法}。

在编写vanilla javascript时,我可以使用onmousedowne.layerX来获取看似正确的数字。但是,在Mozilla文档中,他们建议使用against using it。现在转到React,(在我的特定组件渲染功能中)

e.layerY

我无法再访问return <canvas onMouseMove={ e => this.handleMouseMoved(e) }></canvas>layerX。我也无法访问过去与layerYoffsetX一起使用的clientX来获取鼠标的元素相对坐标。

有许多不同的方法来读取坐标。我很困惑他们的意思以及什么时候应该使用它们。因此,当我将鼠标悬停在左上角时,我希望看到clientY,当我鼠标悬停在右下角时,x: 0, y: 0,我应该查看哪个事件/合成事件?< / p>

1 个答案:

答案 0 :(得分:0)

React使用SyntheticEvents然后&#34; pool&#34;那些提高绩效的事件(https://facebook.github.io/react/docs/events.html#event-pooling

获得&#34; native&#34;事件必须从合成事件中保存,因为React的SyntheticEvent&#34;将被重用,并且在调用事件回调之后所有属性都将无效#34;。

这是什么意思?

local newColor = Color3.new(math.random(255), math.random(255), math.random(255))
for i=0,1,0.1 do
    script.Parent.BackgroundColor3 = script.Parent.BackgroundColor3:lerp(newColor, i)
    wait()
end

<canvas onMouseMove={ e => { let nativeEvent = e.nativeEvent; this.handleMouseMoved(nativeEvent); }></canvas> 会有nativeEventoffsetX/Y等您正在寻找。