【发布时间】:2019-02-24 17:47:39
【问题描述】:
这是我第一次使用 Chartjs,而且我也不是 React 方面的专家。我正在尝试实现一个条形图,该条形图应该可能从 CONST 中获取数据,这些 CONST 是使用用户输入提供的数字的计算器。这就是图表现在的工作方式。 data 中的值是硬编码的,我不知道如何使它们动态化。
constructor(props) {
super(props);
this.state = {
chartData:{},
visitors: "",
conversion: 4,
value: "",
smileeconversion: "",
smileevalue: "",
swcost: "",
labourcost: "",
roi: ""
};
}
componentWillMount(){
this.getChartData();
}
getChartData(){
// Ajax calls here
this.setState({
chartData:{
labels: ['Before', 'After'],
datasets:[
{
label:'Population',
data:[
617594,
181045,
],
backgroundColor:[
'rgba(255, 99, 132, 0.6)',
'rgba(54, 162, 235, 0.6)',
'rgba(255, 206, 86, 0.6)',
'rgba(75, 192, 192, 0.6)',
'rgba(153, 102, 255, 0.6)',
'rgba(255, 159, 64, 0.6)',
'rgba(255, 99, 132, 0.6)'
]
}
]
}
});
}
这是图表组件:
import React, {Component} from 'react';
import {Bar, Line, Pie} from 'react-chartjs-2';
class Chart extends Component{
constructor(props){
super(props);
this.state = {
chartData:props.chartData
}
}
static defaultProps = {
displayTitle:true,
displayLegend: true,
legendPosition:'right',
location:'City'
}
render(){
return (
<div className="chart">
<Bar
data={this.state.chartData}
options={{
title:{
display:this.props.displayTitle,
text:'Return of investments',
fontSize:25
},
legend:{
display:this.props.displayLegend,
position:this.props.legendPosition
}
}}
/>
</div>
)
}
}
export default Chart;
及其父组件:
<Chart chartData={this.state.chartData} location="Massachusetts" legendPosition="bottom"/>
【问题讨论】:
-
据我所知,您是否只加载了一次 chartData。 ComponentWillMount 只被调用一次。您可以在用户更新输入字段时使用 setstate,然后调用 getChartData 函数。
-
你在谈论“数据中的值是硬编码的,我不知道如何使它们动态化”。你说的是数据:[617594, 181045,], ?
-
这些动态数据从何而来?在 AJAX 调用中?如果是这样,我建议在此页面顶部的搜索框中搜索“AJAX ReactJS”。看起来很多人都问过这个话题,并得到了很好的答案。祝你好运!
-
@StephanHovius 是的,这就是我的意思,如果我说得不对,请见谅。
-
@AndyTaton 不,我没有使用 Ajax,该应用程序的基础是它根据用户输入的数字计算投资回报。之后,它比较两个值并用条形图说明。