reactjs无法将this.pops传递到react图表列表中

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

本文关键字:react 列表 this pops reactjs      更新时间:2023-09-26

我想把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.pops。在这种情况下,我使用this.pop是否正确?

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

试着把道具的结构改成这样:

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

从本质上讲,这是将一个带有标签和序列键的对象传递给您的子组件。外部大括号意味着它们内部的所有内容都将被评估为JavaScript。所以我们放了更多的大括号来表示我们正在传递一个对象。

现在,在您的嵌套组件上,您应该可以访问以下结构。操作:

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

然而,由于您的父状态的结构与此图表图表所需的完全相同(具有标签数组和序列数组),如果您想直接传递图表图表的数据对象,请执行以下操作:

<BarChart data={this.state} />

你可以这样渲染你的图形:

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