[英]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.