1

我想将 this.state 从“main.js”(父组件)传递到“bar.js”(子组件)。

//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 和 this.props,我仍然有些困惑。在这种情况下,我是否使用 this.props 正确地接近它?

4

1 回答 1

2

根据您传递它们的方式,您的道具的结构不像您期望的那样。

尝试将道具的结构更改为如下所示:

<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'} />
于 2016-05-13T02:25:24.677 回答