2016-05-13 79 views
1

我想将“main.js”(父组件)的this.state传递给“bar.js”(子组件)。reactjs无法将this.props传递给react-chartist

//main.js 

    import React, { Component } from 'react'; 
    import BarChart from './Bar-chart'; 

    class Hero extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     labels: ['P1', 'P2', 'P3', 'P4', 'P5/P6'], 
     series: [[ 1, 2, 3, 4, 5 ]] 
    } 
    } 

    render() { 

    return (
     <div className="header"> 
     <div className="container"> 
      <div className="row"> 
       <BarChart data={this.props.labels, this.props.series}/> 
      </div> 
      </div> 
     </div> 
     </div> 
    ); 
    } 
}; 

export default Hero; 

这里是我的子组件:

//bar.js 

import React, { Component } from 'react'; 
import ChartistGraph from 'react-chartist'; 
import Legend from 'chartist-plugin-legend'; 

class BarGraph extends Component { 
    constructor(props) { 
    super(props); 

    } 

    render() { 
    const option = { 
     height: '350px', 
     plugins: [ 
     Legend({ 
      legendNames: ['P1', 'P2', 'P3', 'P4', 'P5/P6'], 
     }) 
     ] 
    }; 

    return (
     <ChartistGraph 
      data={this.props.labels, this.props.series} 
      options={option} 
      type={'Bar'} /> 
    ); 
    } 

    barData() { 
    return ({ 
     labels: ['P1', 'P2', 'P3', 'P4', 'P5/P6'], 
     series: [[ 8, 28, 40, 25, 9 ]] 
    }); 
    }; 
} 

export default BarGraph; 

此外,我还在之间时,我应该使用this.state VS this.props有点糊涂了。在这种情况下,我是否正确使用this.props来处理它?

+1

如果标签的值,一系列组件在运行时基于用户交互或其他外部条件发生变化,那么它更好地使用状态,因为然后将新值设置为状态会自动渲染组件。如果标签的值,组件系列是恒定的,并且在其初始渲染之后永远不会改变,那么它最好只使用道具。 –

回答

1

您的道具并不像您期望的那样根据您如何传递给他们的方式进行组织。

试着改变你的道具的结构是这样的:

<BarChart data={{ labels: this.props.labels, series: this.props.series}}/> 

基本上就是这样做的是传下来的对象与标签的钥匙,和系列的子组件。外括号意味着它们中的所有内容都将被评估为JavaScript。所以我们放置更多的大括号来表明我们正在传递一个对象。

现在您的嵌套的组件上,你应该有机会获得以下结构this.props:

this.props = { 
    series: [], 
    labels: [] 
} 

但是,因为你的父母状态的结构完全一样,你需要为这个图表制作图(带标签阵列等一系列阵列),如果你想直接传递下来图表分析数据对象只是这样做:

<BarChart data={this.state} /> 

,你可以使你的图如下所示:

 <ChartistGraph 
      data={this.props} 
      options={option} 
      type={'Bar'} /> 
+0

请让我知道这是否回答您的主要问题 – jmancherje

+0

谢谢,这确实回答了我的问题。 –