尝试导入 chartjs-plugin-datalabels 时出现错误“TypeError:无法读取未定义的属性‘扩展’”

问题描述

错误文本:“TypeError:无法读取未定义的属性‘extend’ (匿名函数) ./node_modules/chartjs-plugin-datalabels/dist/chartjs-plugin-datalabels.js:587"

print of the error i'm getting

这是我尝试导入包的组件。

import { Divider } from "@material-ui/core";
import { Bar } from "react-chartjs-2";
import "chartjs-plugin-datalabels";

const FieldsData = (props) => {
  const getFirstChart = () => {
    const labels = props.fails
      ? props.fails.failsByOcurrence.map((fail) => {
          return fail.label;
        })
      : [];
    const colors = ["#e8e15f","#e8e15f","#e64f3e","#e64f3e"];
    const data = {
      labels,datasets: [
        {
          label: "Intensidade de falhas por intervalo de comprimento",barPercentage: 0.6,data: props.fails
            ? props.fails.failsByLengthClass.map((x) => {
                return x.value;
              })
            : [],backgroundColor: colors,},],};
    const chartConfig = {
      data: data,options: {
        responsive: false,plugins: {},};
    return (
      <div style={{ width: "90%",margin: "0 auto" }}>
        <Bar data={data} options={chartConfig} />
      </div>
    );
  };

  return (
    <div>
      <Divider style={{ margin: "0.5rem 0" }} />
      {getFirstChart()}
    </div>
  );
};

export default FieldsData;

我尝试使用

解决方法

同样的现象发生在我身上。

我认为这个讨论会有所帮助。 https://github.com/chartjs/chartjs-plugin-datalabels/discussions/213#:~:text=chart.js%203%20compatibility

问题可能是 Chart.js 版本 3 和 chartjs-plugin-datalabels 主分支版本之间的依赖关系。

我用这个命令解决了问题

npm install -S chartjs-plugin-datalabels@next

这就是我的依赖项的工作方式。

"chart.js": "^3.3.2","chartjs-plugin-datalabels": "^2.0.0-rc.1","react-chartjs-2": "^3.0.3",

我希望这会有所帮助。

,

我找到了解决方案

需要注册chartDataLabel

import { Bar,Chart } from "react-chartjs-2";
import ChartDataLabels from "chartjs-plugin-datalabels";
Chart.register(ChartDataLabels); // REGISTER PLUGIN
  const data = {
    labels: labels,datasets: [
      {
        label: 'label',data: data,backgroundColor: [
          'rgba(255,99,132,0.2)','rgba(54,162,235,'rgba(255,206,86,'rgba(75,192,'rgba(153,102,255,159,64,],borderColor: [
          'rgba(255,1)',borderWidth: 1,datalabels: {
          color: '#FFCE56',anchor: 'end',align  : 'start',color: function(context) {
            return context.dataset.backgroundColor;
          },font: function(context) {
            var w = context.chart.width;
            return {
              size: w < 512 ? 12 : 14,weight: 'bold',};
          }
        }
      },};
return (
<Bar data={data}/>
)

这篇文章帮助我找到解决方案

chartjs-plugin-zoom not working with my React project