【问题标题】:How to use options in Chart js v3 custom plugin如何在 Chart js v3 自定义插件中使用选项
【发布时间】:2022-08-02 21:50:10
【问题描述】:

我正在按照官方documentation 的说明创建自定义插件。

我正在使用 TypeScript 和 React。

目前,我正在尝试使用一个虚拟插件来记录控制台消息。当我直接在图表(内联)中定义插件时,它可以正常工作。但是,当我尝试在选项中包含插件的选项时,它会显示 Typescript 错误。

错误如下:

Type \'{ pluginPlugin: {}; }\' is not assignable to type \'_DeepPartialObject<PluginOptionsByType<\"line\">>\'.
  Object literal may only specify known properties, and \'pluginPlugin\' does not exist in type \'_DeepPartialObject<PluginOptionsByType<\"line\">>\'

我认为我所有的问题都与 TypeScript 相关,因为如果我只是忽略 ts 错误,我可以看到插件正常工作。

dummy插件的代码如下

const dummyPlugin = {
    id: \'pluginPlugin\',
    afterDraw: function() {
        console.log(\"afterDraw\");
    }
}

我使用内联插件的图表代码摘录如下:

const myChart = new Chart(node, {
                type: \'line\',
                data: {datasets: [], labels: []},
                plugins: [dummyPlugin],
                options: {}
});

在这种情况下,插件会正确记录。

但是,当我尝试为插件添加一些选项时,会出现上述错误。

const myChart = new Chart(node, {
                type: \'line\',
                data: {datasets: [], labels: []},
                plugins: [dummyPlugin],
                options: {
                    plugins: {
                        pluginPlugin: {}
                    }
                }
});

    标签: reactjs typescript charts


    【解决方案1】:

    可以在文档的New Charts 部分找到答案,您需要扩展 chart.js 提供的选项。

    为此,您需要将index.d.ts 文件添加到您的项目中,您可以在其中添加以下内容:

    import {ChartType, Plugin} from 'chart.js';
    
    declare module 'chart.js' {
      interface PluginOptionsByType<TType extends ChartType> {
        pluginPlugin?: { // Key is the pluginId
          customOption1?: boolean;
        }; 
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-01
      • 2019-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多