我正在尝试使用Chartjs和React绘制图表。在值(数组)更新之前,它应该为空。我能够成功更改该值,但图表不会绘制新的条形图。 calcInfo()正确更新颜色和标签。我对React还是很陌生,并且尝试了很多不同的东西,但是还没到任何地方。我一直在尝试所有我能想到的东西,其中还有一些额外的调用和变量。
var scores = [50];
var count = [];
var colors = [];
var border= [];
class BarGraph extends React.Component {
constructor(props) {
super(props);
this.state = {
data:[]
}
scores = [this.state.data];
this.drawChart = this.drawChart.bind(this);
this.handleChange = this.handleChange.bind(this);
}
drawChart() {
var barChart = new Chart(document.getElementById("bar-chart"), {
type: 'bar',
labels: count,
datasets: [
{
label: 'Data',
data: [this.state.data],
backgroundColor: colors,
borderColor: border,
borderWidth: 2,
}
],
options: {
responsive: true,
mode: null,
legend: { display: false },
scales: {
yAxes: [{
stacked: true,
gridLines: {
display: true,
color: "rgba(201,201,201)"
},
ticks: {
beginAtZero: true,
max: 100
}
}]
}
}
})
}
componentDidUpdate() {
this.drawChart();
}
componentDidMount() {
}
handleChange(e) {
var scoreValue;
scoreValue = document.getElementById("data").value;
e.preventDefault();
scoreValue = 50;
scores = [scoreValue];
this.calcInfo();
this.state = {data: [scoreValue]};
this.setState(this.state);
this.componentDidUpdate();
console.log(this.state.data);
console.log(scores);
alert("hello")
}
calcInfo() {
for (var i = 0; i < scores.length; i++) {
var ref1 = 0;
var ref2 = 0;
if (scores[i] <= 10) {
ref1 = 255;
ref2 = 30;
} else if (scores[i] <= 20) {
ref1 = 220;
ref2 = 53;
} else if (scores[i] <= 30) {
ref1 = 180;
ref2 = 75;
} else if (scores[i] <= 40) {
ref1 = 150;
ref2 = 87;
} else if (scores[i] <= 50) {
ref1 = 115;
ref2 = 100;
} else if (scores[i] <= 60) {
ref1 = 90;
ref2 = 120;
} else if (scores[i] <= 70) {
ref1 = 50;
ref2 = 145;
} else if (scores[i] <= 80) {
ref1 = 25
ref2 = 180;
} else if (scores[i] <= 90) {
ref1 = 0;
ref2 = 220;
} else if (scores[i] <= 100) {
ref1 = 0;
ref2 = 255;
}
colors[i] = 'rgba(' + ref2 + ',' + ref1 + ',0, 0.7)';
border[i] = 'rgba(' + ref2 + ',' + ref1 + ',0, 1)';
count[i] = i + 1;
}
}
render() {
this.calcInfo();
return (
<div style={{flex:1}}>
<input id="data" onChange={this.drawChart.bind(this)}/>
<canvas style={{height:'500px'}} id="bar-chart" width="100%" redraw></canvas>
</div>
)
}
}
function mapStateToProps(state) {
return {
'mapData' : state.mapData,
'chartData' :state.chartData
}
}
function mapDispatchToProps(dispatch) {
return {
}
}
export default connect(
mapStateToProps, mapDispatchToProps
)
ReactDOM.render(<BarGraph />,
document.getElementById('root')
);