无法在 onClick 函数中调用任何函数 chart.js

can't call any function inside of onClick function chart.js

我无法调用 chart.js 的 onClick 函数内部的任何函数。甚至无法更改 public 变量值。

initializeGraph() {
 this.graph = new Chart('graph', {
  type: 'pie',
   data: {
    datasets: [{
     data: [1,2],
      backgroundColor: ['#RRGGBB', '#FF0000'],
     }],
      labels: ['blue','red']
    },
   options: {
    onClick : function(event,elements) {
     this.hello();
    }
   }
  });
 }

 hello() {
  console.log("i am here");
 }

你试过使用箭头函数吗? (e) => {} 使用箭头函数时 this 变量的范围不同。 箭头函数从父作用域继承“this”,在您的情况下,它可能指的是全局作用域。

你可以试试吗

initializeGraph() {
    const that = this;
    this.graph = new Chart('graph', {
        type: 'pie',
          data: {
            datasets: [{
              data: [1,2],
              backgroundColor: ['#RRGGBB', '#FF0000'],
            }],
            labels: ['blue','red']
          },
          options: {
           onClick : function(event,elements) {
              that.hello();
            }
          }
     });

}