首页 > 解决方案 > 将标签数组放入chartjs?

问题描述

我有这些代码: let arr = [];

  items &&
    items.map((index) => {
      arr.push(index.itemName);
    });

console.log(arr);表明:

[“项目 1”、“项目 2”、“项目 3”、“项目 4”]

下面是我的图表:如何循环遍历arr要放在标签内的对象?

   <Pie
        data={{
          labels: , <-- How can I loop through all of the `arr` here?
          datasets: [
            {
              label: "1st Dose",
              data: [10, 20, 30, 50, 30],
              backgroundColor: ["red", "orange", "yellow", "Green", "Blue"],
              borderColor: ["rgba(255, 99, 132, 1)"],
              borderWidth: 1,
            },
          ],
        }}
        height={400}
        width={600}
        options={{
          maintainAspectRatio: false,
          title: {
            display: true,
            text: "Hello",
            fontSize: 20,
          },
          legend: {
            labels: {
              fontSize: 25,
            },
          },
        }}
      />

标签: javascriptreactjschartschart.js

解决方案


图表标签接收一个字符串或字符串数​​组:

interface ChartData {
  labels?: Array<string | string[]>;
  datasets?: ChartDataSets[];
}

因此,您将数组直接放在标签上,如下所示:

data={{
  labels: arr,
  datasets: [
    {
      label: "1st Dose",
      data: [10, 20, 30, 50, 30],
      backgroundColor: ["red", "orange", "yellow", "Green", "Blue"],
      borderColor: ["rgba(255, 99, 132, 1)"],
      borderWidth: 1,
    },
  ],
}}

一个活生生的例子供你学习:

编辑 chart.js(分叉)


推荐阅读