我开始学习React和Chart JS但是我被卡住了,因为我无法通过点击按钮更改数据,最初的图表是:
var Datas = [65,59,80,81,56,55,69];
但我想按下按钮更改该图表,我搜索了很多信息,我尝试了几种方法,但它没有用。
任何帮助?
var Labels = ["2010", "2011", "2012", "2013", "2014", "2015", "2016"];
var Datas = [65, 59, 80, 81, 56, 55, 69];
const data = {
labels: Labels
datasets: [{
data: Datas,
backgroundColor: [
'#FF6384',
'#36A2EB',
'#FFCE56'
],
hoverBackgroundColor: [
'#FF6384',
'#36A2EB',
'#FFCE56'
]
}]
};
const legendOpts = {
display: true,
position: 'top',
fullWidth: true,
reverse: false,
labels: {
fontColor: 'rgb(255, 99, 132)'
}
};
export default React.createClass({
displayName: 'LegendExample',
componentWillMount(){
this.setState(data);
},
getInitialState() {
return {
legend: legendOpts,
}
},
changeData() {
const { value } = this.legendOptsInput;
var oldDataSet = this.state.datasets[0];
var newData = [65, 59, 80, 81, 56, 55, 69];
var newDataSet = {
...oldDataSet
};
newDataSet.data = newData;
console.log('this is:', newDataSet.data);
var newState = {
...data,
datasets: [newDataSet]
};
try {
const opts = JSON.parse(value);
this.setState({
//legend: opts;
newState
});
} catch(e) {
alert(e.message);
throw Error(e);
}
},
render() {
return (
<div>
<h2>Example</h2>
<textarea
cols="40"
rows="15"
ref={input => { this.legendOptsInput = input; }}
defaultValue={JSON.stringify(this.state.legend, null, 2)}></textarea>
<div>
<button onClick={this.changeData}>Change data!</button>
</div>
<Line data={this.state} legend={this.state.legend} redraw />
</div>
);
}
})
&#13;
答案 0 :(得分:0)
看起来你将状态初始化为数据对象,但是然后将newData设置为state的属性,而不是替换整个状态对象。
function createYears( start , end ) {
"use strict";
var years;
document.write("<select>");
for (years = start ; years <= end ; years = years + 1){
document.write(`"<option>"` + years + `"</option>"`);
}
document.write("</select>");
}
更改为:
this.setState({
//legend: opts;
newState
});
this.setState(newState)
&#13;