首页 > 解决方案 > 如何用不同的数据渲染单个反应组件?

问题描述

我创建了Barchart作为子组件的组件(显示条形图)。在父组件中,我传递propsBarchart组件。在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>
)

我可以在击球页面(即击球组件)上看到条形图,但在保龄球页面(即保龄球组件)上没有显示任何内容。

标签: javascriptreactjs

解决方案


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每个组件都是独一无二的,而如果你使用类,它可能会与另一个组件发生冲突。


推荐阅读