2016-09-07 51 views
1

我试图添加一个条形图到我的应用程序与现在的任意数据,但我无法得到它呈现。它的输入正确,我使用了chart.js网站的示例代码,但没有运气。我错过了什么?为什么此条形图使用chart.js不在react.js中呈现?

import Chart from 'chart.js'; 
import React, { Component } from 'react'; 

class ChartTeamOne extends Component { 
setState(){ 
    const t1ChartEl= document.getElementById("teamOneCanvas"); 
    let teamOneChart = new Chart(t1ChartEl,{ 
    type: 'bar', 
    data: { 
    labels: ["Red", "Blue"], 
    datasets: [{ 
     label: '# of Votes', 
     data: [12, 19], 
     backgroundColor: [ 
      'rgba(255, 99, 132, 0.2)', 
      'rgba(54, 162, 235, 0.2)', 
     ], 
     borderColor: [ 
      'rgba(255,99,132,1)', 
      'rgba(54, 162, 235, 1)', 
     ], 
     borderWidth: 1 
    }] 
}, 
options: { 
    scales: { 
     yAxes: [{ 
      ticks: { 
       beginAtZero:true 
      } 
     }] 
    } 
} 
}); 
} 
render(){ 
return(
    <canvas id="teamOneCanvas"></canvas> 
); 
} 
} 

export default ChartTeamOne; 

回答

1

chart.js需要一个画布“覆盖”它才能绘制图表。你有正确返回画布的部分。但您正在寻找的功能是componentDidMount()而不是setState()。我以他们的饼图为例,并为它创建了一个反应类。更改代码以匹配更改应该非常简单。

import Chart from 'chart.js'; 
import React, { 
    Component 
} from 'react'; 

export default class PieChart extends Component { 
    componentDidMount() { 
     debugger; 
     const ctx = document.getElementById("pie-chart"); 
     const data = { 
      labels: [ 
       "Red", 
       "Blue", 
       "Yellow" 
      ], 
      datasets: [{ 
       data: [300, 50, 100], 
       backgroundColor: [ 
        "#FF0000", 
        "#0000FF", 
        "#FFCE56" 
       ], 
       hoverBackgroundColor: [ 
        "#FF6384", 
        "#36A2EB", 
        "#FFCE56" 
       ] 
      }] 
     }; 
     const pieChart = new Chart(ctx, { 
      type: 'pie', 
      data: data 
     }); 
    } 
    render() { 
     return (
      <canvas id="pie-chart"></canvas> 
     ); 
    } 
}