首页 > 解决方案 > 事件发出错误

问题描述

所以我有这个代码 -

@Component({
  tag: "app-home",
  styleUrl: "app-home.css"
})
export class AppHome {
  @Event()
  myEvent: EventEmitter;

  callEv() {
    this.myEvent.emit("hello");
  }

  render() {
    return (
      <div class="app-home">
        <button onClick={this.callEv}>Hello</button>
      </div>
    );
  }
}

单击按钮时,我在控制台中收到此错误-

未捕获的类型错误:无法读取未定义的属性“发出”
    在 HTMLButtonElement.callEv

知道为什么吗?

标签: stenciljs

解决方案


callEv方法内部,您使用this关键字来调用事件发射器服务。但是在模板内部,上下文不同,因此this不包含事件发射器服务,这会导致您的错误。

您需要做的是将当前上下文绑定到该方法。将此添加到您的课程中:

constructor() {
    this.callEv = this.callEv.bind(this);
}

推荐阅读