react-chartjs-2 工具提示回调不工作

react-chartjs-2 tooltip callback not working

我正在使用 react-chartjs-2 库在 React 中制作简单的图表。我尝试通过添加标题来自定义一些工具提示:

tooltips: {
    callbacks: {
      label: (tooltipItem, data) => {
        return tooltipItem?.value + ' test';
      }
    }
  }

代码沙盒:https://codesandbox.io/s/zealous-mestorf-ste8u
尽管我遵循了 chart.js 示例以及许多其他自定义工具提示示例(即这个问题的答案:React-chartjs-2: Pie Chart tooltip percentage,但代码不起作用 ).

您在使用 v3 时使用了 v2 语法,因此选项名称和位置错误,而且您的比例配置错误,它应该如下所示:

const option = {
  plugins: {
    tooltip: {
      callbacks: {
        title: function () {
          return "my tittle";
        }
      }
    },
    legend: { display: false },
    title: {
      display: true,
      text: "Test chart",
      position: "top"
    }
  },
  scales: {
    y: {
      beginAtZero: true
    }
  }
};

有关 v2 和 v3 之间变化的更多信息,请查看 migration guide