如何在 Reactjs 组件中使用普通 JavaScript?

sto*_*ock 5 javascript reactjs

我正在使用chartist.js,并且我正在reactjs组件中使用chartist。我指的是这个http://gionkunz.github.io/chartist-js/examples.html#simple-pie-chart

图表师.js:

var Chartist = {
    version:'0.9.5' 
}

(function (window, document, Chartist) {

var options = {
  labelInterpolationFnc: function(value) {
    return value[0]
  }
};

var responsiveOptions = [
  ['screen and (min-width: 640px)', {
    chartPadding: 30,
    labelOffset: 100,
    labelDirection: 'explode',
    labelInterpolationFnc: function(value) {
      return value;
    }
  }],
  ['screen and (min-width: 1024px)', {
    labelOffset: 80,
    chartPadding: 20
  }]
];

})();
Run Code Online (Sandbox Code Playgroud)

Reactjs组件:

import React, { Component } from 'react';

var data = {
  labels: ['Bananas', 'Apples', 'Grapes'],
  series: [20, 15, 40]
};

showPieChart(data){
     new Chartist.Pie('.ct-chart', data, options, responsiveOptions);
}

class Chart extends Component {

  render(){
    return(
      <div>
          <div className="center">
              {showPieChart}
          </div>
      </div>

    )}

}

export default Chart;
Run Code Online (Sandbox Code Playgroud)

网页上不显示任何内容。如何访问 React 组件内的普通 JavaScript。

Jor*_*nev 3

你的问题有点误导,可以用两种方式解释。

#1. 如果您询问如何将 Chartist 库与 React 集成,请按以下步骤操作:

有一个包装库,已经为我们完成了:https ://www.npmjs.com/package/react-chartist

您可以按如下方式使用它(示例取自他们的存储库):

import React from 'react';
import ReactDOM from 'react-dom';
import ChartistGraph from 'react-chartist';

class Pie extends React.Component {
  render() {

    var data = {
      labels: ['W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8', 'W9', 'W10'],
      series: [
        [1, 2, 4, 8, 6, -2, -1, -4, -6, -2]
      ]
    };

    var options = {
      high: 10,
      low: -10,
      axisX: {
        labelInterpolationFnc: function(value, index) {
          return index % 2 === 0 ? value : null;
        }
      }
    };

    var type = 'Bar'

    return (
      <div>
        <ChartistGraph data={data} options={options} type={type} />
      </div>
    )
  }
}

ReactDOM.render(<Pie />, document.body)
Run Code Online (Sandbox Code Playgroud)

#2. 如果您通常询问如何将其他库集成到 React 中,那么我建议您查看官方 React 文档,因为有一个关于该主题的非常好的教程 -与其他库集成

因此,如果您不想使用包装器库(react-chartist),那么您也可以检查其主要组件。这是了解如何创建自己的包装器的一个很好的起点(遵循 React 建议): https: //github.com/fraserxu/react-chartist/blob/master/index.js