简体   繁体   中英

reactjs unable to pass down this.props into react-chartist

I would like to pass this.state from "main.js" (parent component) into "bar.js" (child component).

//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;

Here is my child component:

//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;

In addition, I am still a bit confused between when I should use this.state vs this.props. In this scenario, am I approaching it correctly using this.props?

Your props are not structured as you expect based on how you passed them down.

Try changing the structure of your props to look like this:

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

essentially what this is doing is passing down an object with the keys of labels, and series to your child component. The outer braces mean that everything inside of them will evaluated as JavaScript. So we put more braces to indicate we're passing down an object.

Now on your nested component you should have access to the following structure for this.props:

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

However, because your parent state is structured exactly as you need for this chartist graph (with a labels array and a series array), if you want to pass down the data object for chartist directly just do this:

<BarChart data={this.state} />

and you can render your graph like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM