gpt4 book ai didi

javascript - React - 左键单击未触发 onMouseDown/onMouseUp

转载 作者:太空宇宙 更新时间:2023-11-04 15:52:11 25 4
gpt4 key购买 nike

我正在 React 组件中处理 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 坐标。

最佳答案

您可以使用 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')
);
.chart {
width: 100;
height: 100;
}

#canvas {
border: 1px black solid;
width: 50;
height: 50;
background-color: blue;
}
<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>

关于javascript - React - 左键单击未触发 onMouseDown/onMouseUp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49262790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com