我在反应组件中的HTML Canvas上处理鼠标事件,但是在左键单击鼠标时没有触发onMouseDown / onMouseUp的问题。它适用于右键单击和中心点击。
handleMouseDown(event)
{
console.log("mouse down");
}
handleMouseMove(event)
{
console.log("mouse move");
}
handleMouseUp(event)
{
console.log("mouse up");
}
render() {
return (
<div
className="chart">
<canvas
id="canvas"
onMouseDown={this.handleMouseDown}
onMouseMove={this.handleMouseMove.bind(this)}
onMouseUp={this.handleMouseUp.bind(this)} />
</div>
);
以前有人经历过这个吗?
修改 注意:我正在尝试获取鼠标停止事件发生位置的X / Y坐标。
答案 0 :(得分:3)
您可以使用onClick
进行左键点击:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(event){
const yCoord = event.y;
const xCoord = event.x;
console.log("Y Coordinate = " + yCoord +
"\n X Coordinate = " + xCoord + ".");
switch(event.which){
case 1: {
console.log('Left Mouse button pressed.');
break;
}
case 2: {
console.log('Middle Mouse button pressed.');
break;
}
case 3: {
console.log('Right Mouse button pressed.');
break;
}
default: {
console.log('You have a strange Mouse!');
}
}
}
render() {
return (
<div className="chart">
<canvas id="canvas"
onClick={(e) =>{this.handleClick(e.nativeEvent)}}
onContextMenu={(e) =>
{this.handleClick(e.nativeEvent)}}></canvas>
</div>
);
}
}
ReactDOM.render(
<MyComponent />,
document.getElementById('container')
);
&#13;
.chart {
width: 100;
height: 100;
}
#canvas {
border: 1px black solid;
width: 50;
height: 50;
background-color: blue;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
&#13;