我对此问题感到困惑。
我在http://codepen.io/anon/pen/ZOKpxQ上尝试了它,但它不起作用,但不适用于我的VisualResults.jsx
我想知道它是否可能是我失踪的东西?
非常感谢! :)
var React = require('react');
var BarChart = require('react-chartjs').Bar;
var Chart = require('chart.js');
var VisualResults = React.createClass({
render: function(){
var piechart = document.getElementById("myChart");
var myPieChart = new Chart(piechart,
{
type: 'pie',
data: {
labels: [
"Red",
"Blue",
"Yellow"
],
datasets: [
{
data: [300, 50, 100],
backgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}]
},
options: {
responsive: true
}
});
return(
<canvas id="myChart" width="600" height="400"></canvas>
)
}
});
module.exports = VisualResults;
答案 0 :(得分:0)
我相信答案是标签出现在试图获取上下文的图表代码之后。下面是一个 HTML 页面的示例,其中正确放置了标记。检查 chartjs 文档后,它似乎没有明确说明脚本和标签顺序的重要性。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chart Test App</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</head>
<body>
<b>Chart Example</b>
<!-- It's critically important that the <canvas> tag appears before the script where the chart context is created
If the <canvas> tag appears after the chart context you will receive a
"Uncaught TypeError: Cannot read property 'length' of null" error -->
<canvas id="myChart"></canvas>
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
</body>
</html>