我想使用ChartJS在REACT JS中一起绘制实线和虚线类似“ https://jsfiddle.net/3gxjfndm/3/”。由于无法获取上下文(ctx),我无法理解如何在我的react js文件中扩展图表。我了解基本概念,但无法在我的React Component上实现。
以下是我的折线图实现,我认为这是一个BAD实现。
import Chart from 'chart.js';
class LineChart extends React.Component {
constructor(props) {
super(props);
this.canvasRef = React.createRef();
}
componentDidMount() {
this.myChart = new Chart(this.canvasRef.current, {
type: 'line',
options: {
responsive: true,
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
legend:{
display:false,
},
scales: {
x: {
display: true,
scaleLabel: {
display: true,
labelString: 'Month'
}
},
y: {
display: true,
scaleLabel: {
display: true,
labelString: 'Value'
}
}
}
},
data: {
labels: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'],
datasets: [{
label: "My First dataset",
data: [1, 8, 3, 4, 2, 3, 4],
borderColor: '#66f',
borderDash: [20, 30],
pointBackgroundColor: "transparent"
},{
label: "My Dotted dataset",
data: [null, null, null, null, null, null, 4, 7, 5, 3, 2],
borderColor: '#66f',
pointBackgroundColor: "transparent"
}]
}
});
}
render() {
return (
<div className="chart-section">
<div className="chart-body">
<canvas ref={this.canvasRef} />
</div>
</div>
)
}
}
export default LineChart;```
您可以使用react-chartjs-2 https://github.com/jerairrest/react-chartjs-2,它为React实现chart.js,并且当选项和数据集与chart.js一样时,您可以像任何常规React组件一样调用它。