簡體   English   中英

我如何在 React 項目中正確使用 chartjs?

[英]How do i use chartjs in react project properly?

我試圖在我的 React 項目中使用 chartjs,但它不起作用。 我究竟做錯了什么?

您可以在此處查看控制台日志:

日志

 import styled from "styled-components"; import { Bar } from "react-chartjs-2"; const WeatherChart = () => { return ( <Container> <Bar data={{ labels: ["Red", "Blue"] }} width={100} height={50} options={{ maintainAspectRatio: false }} /> </Container> ); }; const Container = styled.section` height: 50%; width: 100%; display: flex; align-items: center; justify-content: center; `; export default WeatherChart;

您傳遞給Bar的屬性不正確。 具體來說,您的data屬性缺少自己的datasets屬性,如Chart.js嘗試調用setDatasets時的錯誤日志中所示。

假設您要繪制過去一周每一天的溫度圖表:

您的labels屬性:

const labels = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

您的data屬性:

const data = {
  labels,
  datasets: [
    {
      label: 'Temperatures',
      data: labels.map(() => Math.random() * 100),
      backgroundColor: 'rgba(255, 99, 132, 0.5)',
    },
  ],
}

您的options屬性:

const options = {
  responsive: true,
  plugins: {
    legend: {
      position: 'top',
    },
    title: {
      display: true,
      text: 'Chart.js Bar Chart',
    },
  },
}

將它們傳遞給Bar

return <Bar options = {options} data = {data} />

你的圖表:

在此處輸入圖像描述

文檔中了解更多信息並查看更多示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM