使用Charts.js做出反应

11 javascript reactjs chart.js

我正在使用React并希望将其与Chart.js绑定.

下图有效,但我不知道如何在React中创建Graph组件.

我的Chart.js代码如下所示:

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
    labels: ["Red", "Blue", "Yellow"],
    datasets: [{
        label: '# of Likes',
        data: [12, 19, 3],
        backgroundColor: [
           'rgba(255, 99, 132, 0.2)',
           'rgba(54, 162, 235, 0.2)',
           'rgba(255, 206, 86, 0.2)'
        ] 
     }]
   }
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.bundle.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
Run Code Online (Sandbox Code Playgroud)

然后我尝试将其纳入React.不幸的是,这不起作用.

我的代码尝试可以在这里看到.这有点工作,但不是真的,我不知道采取什么方法.

var Graph = React.createClass({

    render: function() {
        var ctx = document.getElementById("myChart");
        var myChart = new Chart(ctx, {
           type: 'bar',
           data: {
           labels: ["Red", "Blue", "Yellow"],
           datasets: [{
               label: '# of Likes',
               data: [12, 19, 3],
               backgroundColor: [
                  'rgba(255, 99, 132, 0.2)',
                  'rgba(54, 162, 235, 0.2)',
                  'rgba(255, 206, 86, 0.2)'
               ] 
            }]
          }
       });
    }
})
Run Code Online (Sandbox Code Playgroud)

Rey*_*hra 21

我一直在使用react-charjsreact-chart-js2,看起来他们有自己的限制,如果你想要更多的控制,你可以直接在你的组件中使用Chartjs.

import React from "react";
var Chart = require("chart.js");

class Layout extends React.Component {
  constructor(props) {
    super(props);
  }
  componentDidMount() {
    const node = this.node;

    var myChart = new Chart(node, {
      type: "bar",
      data: {
        labels: ["Red", "Blue", "Yellow"],
        datasets: [
          {
            label: "# of Likes",
            data: [12, 19, 3],
            backgroundColor: [
              "rgba(255, 99, 132, 0.2)",
              "rgba(54, 162, 235, 0.2)",
              "rgba(255, 206, 86, 0.2)"
            ]
          }
        ]
      }
    });
  }

  render() {
    return (
      <div>
        <canvas
          style={{ width: 800, height: 300 }}
          ref={node => (this.node = node)}
        />
      </div>
    );
  }
}

export default Layout;
Run Code Online (Sandbox Code Playgroud)


Mch*_*chl 2

GitHub 上的 ReactJS 组织提供了一个围绕 ChartJS 的 React 包装器。它确实支持条形图。也许尝试一下(如果不是作为解决方案,那么作为灵感的来源)

  • 注意:此答案中提到的react-chartjs库已存档 (2认同)