javascript - 如何用不同的数据渲染单个反应组件?
问题描述
我创建了Barchart
作为子组件的组件(显示条形图)。在父组件中,我传递props
给Barchart
组件。在Barchart
我使用的组件中if/else
并相应地渲染Barchart
。
条形图组件:
import React, { Component } from 'react';
class Barchart extends Component {
constructor(props){
super(props);
}
componentDidMount(){
if(this.props.statType === 'batting'){
const data1 = {
labels: ['XS', 'S', 'M', 'L', 'XL', 'XXL', 'XXXL'],
series: [20, 60, 120, 200, 180, 20, 10]
}
const options1 = {
width:300,
height:300,
distributeSeries: true
}
const mychart1 = new Chartist.Bar('.ct-bar-chart', data1,options1);
}else if(this.props.statType === 'bowling'){
const data1 = {
labels: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
series: [200, 600, 120, 200, 1800, 200, 100]
}
const options1 = {
width:300,
height:300,
distributeSeries: true
}
const mychart1 = new Chartist.Bar('.ct-bar-chart', data1,options1);
}
}
render(){
return(
<div className="ct-bar-chart">
{this.mychart1}
</div>
)}
}
export default Barchart;
保龄球组件:
return(
<div><Barchart bowldata={this.props} statType='bowling'/></div>
)
击球成分:
return(
<div><Barchart batdata={this.props} statType='batting'/></div>
)
我可以在击球页面(即击球组件)上看到条形图,但在保龄球页面(即保龄球组件)上没有显示任何内容。
解决方案
ref
在初始化图形而不是类时尝试使用in。考虑下面的代码:
render(){
return(
<div className="ct-bar-chart"
ref={(ele) => this.chartElement = ele}>
...
</div>
)}
现在在初始化图表时使用:
const mychart1 = new Chartist.Bar(this.chartElement, data1,options1);
所以这里的优势是this.chartElement
每个组件都是独一无二的,而如果你使用类,它可能会与另一个组件发生冲突。
推荐阅读
- php - PHP输出不同数字组合的值加在一起
- amazon-web-services - AWS SSL 证书续订问题
- animation - 使用 SVG 为圆形边框设置动画的具体方法?
- android - 当回调是类的字段时,将回调转换为suspendCoroutine
- reactjs - 无法在 React 中对列进行排序
- visual-studio-code - 如何修复 IBM DB2 管理连接错误?
- roblox - 我可以在 roblox 的 gui 上使用可绑定事件吗?
- python - 使用 python 请求从网站上抓取信息
- visual-c++ - Clang 在 Windows 上的性能优于 MSVC
- python - 从文本文件中读取多个字典,然后对其进行排序