【发布时间】:2018-03-25 19:45:09
【问题描述】:
我有一个名为 Chart 的 React 组件。我想根据从父级传递的道具在其中呈现不同的图表,但具有完全相同的配置。最好的方法是什么?
class Chart extends Component {
static propTypes = {
type: PropTypes.string.isRequired
}
state = {
chartData: {
// some data here
}
}
render(){
return(
this.props.type === 'line' ?
{ <Line
data={this.state.chartData}
options={{
title: {
display: true,
text: 'Cities I\'ve lived in',
fontSize: 25
},
legend: {
display: true,
position: 'right',
labels: {
fontColor: '#000'
}
}
}}
/> } : this.props.type === 'bar' ?
{ <Bar
//same stuff here as <Line />
/>
} : this.props.type === 'pie' ?
{ <Pie
//same stuff here as <Line />
/> }
}
);
}
}
不要认为这很重要,因为这个问题很笼统,但我正在使用 react-chartjs-2 / chart.js 2 库来呈现图表。
注意:我尝试使用变量名代替 Line/Bar/Pie,但如果我使用 JSX 或呈现非 html 标记,它就不起作用。也欢迎在使用 JSX 和非 html 标记的同时解决它的更好方法。
【问题讨论】:
标签: javascript reactjs chart.js