代码之家  ›  专栏  ›  技术社区  ›  stone rock

如何使用不同的数据呈现单个react组件?

  •  1
  • stone rock  · 技术社区  · 6 年前

    我创造了 Barchart 组件(显示条形图),它是子组件。在父组件中传递 props 柱状图 组件。在 柱状图 我正在使用的组件 if/else 并呈现 柱状图 因此。

    条形图组件:

    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>
    )
    

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

    1 回复  |  直到 6 年前
        1
  •  1
  •   Hriday Modi Victor Manuel    6 年前

    尝试使用 ref 在初始化图形而不是类时。考虑以下代码:

    render(){
        return(
             <div className="ct-bar-chart"
                  ref={(ele) => this.chartElement = ele}>
                  ...
             </div>
        )}
    

    初始化图表时使用:

    const mychart1 = new Chartist.Bar(this.chartElement, data1,options1);
    

    所以这里的优势是 this.chartElement 对于每个组件都是唯一的,而如果使用类,则可能与其他组件冲突。