Cocos Creator 3.5.0(TypeScript)中Button组件CustomEventData的正确用法
在Cocos Creator 3.5.0里,Button组件的CustomEventData不会直接作为回调函数的第一个参数传入,得按规则处理参数结构:
一、编辑器绑定事件场景
如果是在编辑器的Button组件面板里绑定use_powerUp函数,回调需要接收两个参数:第一个是事件对象,第二个才是CustomEventData的内容。修改代码如下:
use_powerUp(event: Event, customData: string){ console.log("MapScreenManager::use_powerUp() 事件对象: ", event); console.log("MapScreenManager::use_powerUp() 自定义数据: ", customData); }
在Button组件的Click Events里完成绑定后,在CustomEventData输入框填入你要传递的字符串(比如"speed_up"),点击按钮就能正确拿到参数。
二、代码动态绑定事件场景
如果用代码动态绑定点击事件,需要通过Button.clickEvents数组添加Component.EventHandler对象并赋值customEventData,回调参数规则和编辑器绑定一致:
import { _decorator, Component, Button, Node, Event } from 'cc'; const { ccclass, property } = _decorator; @ccclass('MapScreenManager') export class MapScreenManager extends Component { @property(Button) testButton: Button = null; onLoad() { // 创建事件处理器 const handler = new Component.EventHandler(); handler.target = this.node; // 回调所在节点 handler.component = 'MapScreenManager'; // 脚本类名 handler.handler = 'use_powerUp'; // 回调函数名 handler.customEventData = 'code_bind_data'; // 自定义数据 // 添加到Button的点击事件列表 this.testButton.clickEvents.push(handler); } use_powerUp(event: Event, customData: string){ console.log("MapScreenManager::use_powerUp() 自定义数据: ", customData); } }
常见误区
你之前只定义一个参数,拿到的其实是事件对象而非自定义数据,这就是参数不符合预期的原因。记住:无论哪种绑定方式,回调函数第一个参数始终是事件对象,CustomEventData是第二个参数。
内容的提问来源于stack exchange,提问作者noobsee
相关产品推荐
相关产品推荐

