如何在Chart.js和react-chartjs-2的自定义插件中传递参数

7z5jn7bk  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(205)

我创建了一个自定义插件horizontalArbitraryLine

import { Plugin } from "chart.js";

export const horizontalArbitraryLine: Plugin = {
    id: "horizontalArbitraryLine",
    beforeDraw(chart, args, options) {
        const {
            ctx,
            chartArea: { top, right, bottom, left, width, height },
            scales: { x, y },
        } = chart;
        ctx.save();
        // console.log(chart, args, options);
        console.log(options.lineColor);
    },
};

我想使用horizontalArbitraryLine自定义插件并将lineColor传递给它

options: {
        plugins: {
            legend: {
                position: "bottom",
            },
            horizontalArbitraryLine: {
                lineColor: "black",
            },
        },
    },

遇到以下问题

Type '{ legend: { position: "bottom"; }; horizontalArbitraryLine: { lineColor: string; }; }' is not assignable to type '_DeepPartialObject<PluginOptionsByType<keyof ChartTypeRegistry>>'.
  Object literal may only specify known properties, and 'horizontalArbitraryLine' does not exist in type '_DeepPartialObject<PluginOptionsByType<keyof ChartTypeRegistry>>'.ts(2322)

我预先感谢你的帮助。

f1tvaqid

f1tvaqid1#

您需要通过创建自己的index.d.ts文件来扩展chart.js类型,并将以下内容放入其中:

import {ChartType, Plugin} from 'chart.js';

declare module 'chart.js' {
  interface PluginOptionsByType<TType extends ChartType> {
    horizontalArbitraryLine?: {
      lineColor: string
    };
  }
}

相关问题