渲染函数中出错(reactjs)?

时间:2018-06-12 16:40:21

标签: javascript reactjs

我正在尝试将chartist.js与我的反应组件一起使用。我无法在反应组件中显示饼图。

Chartist.js - > https://gionkunz.github.io/chartist-js/getting-started.html

Pie.js:

import React, { Component } from 'react';

    var data = {
      // A labels array that can contain any sort of values
      labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
      // Our series array that contains series objects or in this case series data arrays
      series: [
        [5, 2, 4, 2, 0]
      ]
    };

    // Create a new line chart object where as first parameter we pass in a selector
    // that is resolving to our chart container element. The Second parameter
    // is the actual data object.
   const mychart =  new Chartist.Line('.ct-chart', data);

class Pie extends Component {

  render(){
    return(
      <div>
          <div class="ct-chart ct-perfect-fourth">
          {mychart}

          </div>
      </div>

    )}

}

export default Pie;

父组件:

render(){
      return(
<div>
      <Pie/>
</div>     
  )
}

我正在我的父组件中导入Pie.js但是我收到错误,说对象应该是数组而不是对象,objects are not valid react child。看截图: enter image description here

1 个答案:

答案 0 :(得分:1)

@ azium提到的代码存在多个问题,首先在Reactjs中,我们使用className而不是class,因为class是保留关键字JavaScript的。其次,在第一个代码块中,您已将类名称设为Chart并已导出Pie

所以要开始运行,首先要使用Chartist for reactjs,然后按照文档中提到的内容进行操作(比如添加css)。您可以import ChartistGraph from '../index';代替import ChartistGraph from 'react-chartist'。因此,工作图表组件看起来像这样

import React, { Component } from 'react';
import ChartistGraph from 'react-chartist'
    var data = {
      // A labels array that can contain any sort of values
      labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
      // Our series array that contains series objects or in this case series data arrays
      series: [
        [5, 2, 4, 2, 0]
      ]
    };
    var data = {
      labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
      series: [
        [5, 2, 4, 2, 0]
      ]
    };
    var options = {
      high: 10,
      low: -10,
      axisX: {
        labelInterpolationFnc: function(value, index) {
          return index % 2 === 0 ? value : null;
        }
      }
    };
    var type = 'Bar'
class Pie extends Component {
  render(){
    return(
      <div>
        <ChartistGraph data={data} options={options} type={type} />
      </div>
    )}
}
export default Pie;

同时将此内容添加到您的父组件。