【问题标题】:Chart in React is not displayingReact 中的图表未显示
【发布时间】:2022-06-29 14:27:28
【问题描述】:

我在我的 react 应用程序中编写了一个基本的条形图代码,但我在 chrome 或 firefox 浏览器上没有得到任何东西。代码如下::

App.js 文件


import './App.css';
import BarChart from './components/barChart';
function App() {
  return (
    <div className="App">
      <h1>Chart</h1>
       <BarChart />
    </div>
  );
}

export default App;

barChart.js 文件已在 components 文件夹中创建,其编码如下:

import React from 'react'
import {Bar} from 'react-chartjs-2'


const data = {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
    datasets: [
      {
        label: 'My First dataset',
        backgroundColor: 'rgba(255,99,132,0.2)',
        borderColor: 'rgba(255,99,132,1)',
        borderWidth: 1,
        hoverBackgroundColor: 'rgba(255,99,132,0.4)',
        hoverBorderColor: 'rgba(255,99,132,1)',
        data: [65, 59, 80, 81, 56, 55, 40]
      }
    ]
  };
function barChart() {
    
    return (
        <div>
           <h2>Bar Example (custom size)</h2>
        <Bar
          data={data}
          width={100}
          height={50}
          options={{
            maintainAspectRatio: false
          }}
        />
        <h1>Bar Chart</h1>
        </div>
    )
}

export default barChart

我已经安装了 npm install --save react-chartjs-2 chart.js

【问题讨论】:

    标签: reactjs charts


    【解决方案1】:

    如果我没记错的话,React 中的Components 的名字必须大写。

    因此,请尝试 function BarChart(),而不是 function barChart()。记得更正App.js 中的导入。

    【讨论】:

      【解决方案2】:

      您只需要
      从 'chart.js/auto' 导入 { Chart as ChartJS } 你的代码肯定会工作

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-07-20
        • 1970-01-01
        • 1970-01-01
        • 2021-09-12
        • 2017-03-27
        • 2021-03-04
        • 2020-07-25
        相关资源
        最近更新 更多