我有一个名为 Chart 的 React 组件。我想根据从父级传递的 Prop 在其中渲染不同的图表,但具有完全相同的配置。最好的方法是什么?
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 标签来解决这个问题的更好方法。
最佳答案
有两件事:
- 使用无状态组件,在您的示例中您没有使用状态。
- 使用
switch
代替if
语句。
您的新组件 ...chart
是解构的 props。阅读有关解构的更多信息 MDN .
// Chart.js - new component
export const Chart = ({ type, ...chart }) => {
switch(type) {
case 'line':
return <Line {...chart} />
case 'bar':
return <Bar {...chart} />
case 'pie':
return <Pie {...chart} />
default:
return null;
}
}
使用示例
// App.js
render() {
return (
<div>
<Chart type="line" options={optionsObject} whateverProp="whatever" />
<Chart type="bar" options={optionsObject} whateverProp="whatever" />
<Chart type="pie" options={optionsObject} whateverProp="whatever" />
</div>
)
}
关于javascript - 在 React.js 中有条件地渲染不同元素时传递相同的 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49480194/