0

我在一个 gatsby + React 项目中,并直接使用 chart.js 库(即不是反应库)。每当我尝试从 chart.js 扩展基类时,都会出现以下错误:

TypeError:没有'new'就不能调用类构造函数BarController

我的代码是:

import { BarController } from 'chart.js';

export class CustomBarController extends BarController {

    defaults = {
        datasetElementType: null,
        dataElementType: null
    }

    id = 'CustomBar'

    draw() {
        // Call bubble controller method to draw all the points
        super.draw(arguments);  

        // Now we can do some custom drawing for this dataset. Here we'll draw a red box around the first point in each dataset
        const meta = this.getMeta();
        const pt0 = meta.data[0];

        const {x, y} = pt0.getProps(['x', 'y']);
        const {radius} = pt0.options;

        const ctx = this.chart.ctx;
        ctx.save();
        ctx.strokeStyle = 'red';
        ctx.lineWidth = 1;
        ctx.strokeRect(x - radius, y - radius, 2 * radius, 2 * radius);
        ctx.restore();
    }
}

然后我用它:

import { Chart, registerables } from 'chart.js';
import { CustomBarController } from './CustomBarController';

Chart.register(...registerables);
Chart.register(CustomBarController);

let chart = new Chart(ctx, { type: 'CustomBar', data: data, options: props.options });

但是,它总是给出错误。

有没有人认为这是一个盖茨比的事情?也许我需要以不同的方式导入 chart.js 子库吗?或者有没有人在覆盖基类的同时在 gatsby 项目中做 chart.js 的经验?

4

0 回答 0