2016-09-07 135 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> 
     ); 
    } 
}