gpt4 book ai didi

javascript - react : How could we detect user click on canvas?

转载 作者:行者123 更新时间:2023-11-29 20:56:16 25 4
gpt4 key购买 nike

您好,感谢您阅读这个问题。

我有一个用例,我需要在 Canvas 上检测鼠标坐标,感谢@Carlos Martinez:getting mouse coordinates in React它按预期工作。

我尝试更进一步,检测用户是否在 Canvas 上单击,然后使用状态在其上放置一个 h2,并记录它;这是我试过的代码:

import React from 'react';


class Canvas extends React.Component {
//A canvas to display images with a title


constructor(props) {
super(props);

this.state = {x: 0, y: 0, inside: ''};

this.handleClick = this.handleClick.bind(this);
}

_onMouseMove(e) {
this.setState({x: e.nativeEvent.offsetX, y: e.nativeEvent.offsetY});
}

componentDidMount() {
document.addEventListener('click', this.handleClick);
}

componentWillUnmount() {
document.removeEventListener('click', this.handleClick);
}

handleClick(e) {
console.log('INSIDE');
this.setState({inside: 'inside'});
}

render() {

const {x, y, inside} = this.state;

return (
<div className="previewComponent">
<div className="imgPreview">
{this.props.title}
<img src={this.props.image} alt="" onMouseMove={this._onMouseMove.bind(this)}
onClick={this.handleClick.bind(this)}/>
<h1>Mouse coordinates: {x} {y}</h1>
<h2>Inside?: {inside}</h2>
</div>
</div>
)
}
}

export {Canvas};

我预计它只会记录一次,并将其放在 h2 标签上。

然而,出乎意料的是它记录了 INSIDE,然后另外记录了两个 INSIDE:

INSIDE
2 Canvas.js:29 INSIDE

你能解释一下这种行为吗?此外,我们将不胜感激一些修复它的提示,并且每次点击只打印一个日志!

编辑:

我已经尝试过@Or B 的回答并且我理解它但是它看起来仍然显示相同的行为,3 个 INSIDE 日志而不是一个:

enter image description here

代码是:

 handleClick(e) {
e.stopPropagation();
console.log('INSIDE');
this.setState({inside: 'inside'});
}

最佳答案

发生这种情况是由于事件传播以及您正在收听 click 的事实整个文档的事件。

点击 <img>不仅生成一个click事件为图像,也为两个包装<div>元素。这两个被文档捕获,这就是它被记录两次的原因。如果你登录e.target您可以看到哪个元素触发了事件。

为了防止传播,使用event.stopPropagation() :

handleClick(e) {
e.stopPropagation();
console.log('INSIDE');
this.setState({inside: 'inside'});
}

关于javascript - react : How could we detect user click on canvas?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49195278/

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