[英]How to call a function in one React component by button click in another component
[英]How to call a function on a click on a component?
function component(width, height, source, x, y) {
this.image = new Image();
this.image.src = source;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.drawImage(this.image,
this.x,
this.y,
this.width, this.height);
}
this.newPos = function(a, b, image, h) {
this.x = a;
this.y = b;
this.image.src = image;
this.height = h;
}
}
单击组件后如何调用函数? 还是我应该只记录点击的坐标并将其与组件的坐标进行比较?
不幸的是,使用HTML5 Canvas时,没有单个节点可以注册click事件。 您唯一真正的选择是在<canvas>
元素本身上注册一个click事件,然后使用X和Y坐标确定单击了哪个组件。
我不知道您使用的是香草JS还是特殊的引擎,但是如果您可以使用JQuery,也许您必须看看这个https://api.jquery.com/click/ ,它允许您每次执行一个函数单击您的组件,下面的代码仅是有关如何使用该功能的示例,请对其进行测试以确保它对您有用
function component(width, height, source, x, y) {
this.image = new Image();
this.image.src = source;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.drawImage(this.image,
this.x,
this.y,
this.width, this.height);
}
this.newPos = function(a, b, image, h) {
this.x = a;
this.y = b;
this.image.src = image;
this.height = h;
}
$(this).click(function(){
//Code here
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.