2015-06-10 116 views
0

我想了解React如何工作。如何从github导入React组件?

我想使用react-chartjs库。 (https://github.com/jhudson8/react-chartjs)。我如何将其导入到我的项目中?

我试图以这种方式:在一个文件MyComponent.js

var LC = React.createClass({ 
render: function(){ 
    var xfield = this.props.xfield; 
    var yfield = this.props.yfield; 
    var data = { 
      labels: xfield, 
      datasets: [ 
      { 
       label: "My First dataset", 
       fillColor: "rgba(220,220,220,0.2)", 
       strokeColor: "rgba(220,220,220,1)", 
       pointColor: "rgba(220,220,220,1)", 
       pointStrokeColor: "#fff", 
       pointHighlightFill: "#fff", 
       pointHighlightStroke: "rgba(220,220,220,1)", 
       data: yfield 
      }] 
     } 


    return(
     <LineChart data={data} width="600" height="250" /> 
    ); 

}}); 


var MyComponent = React.createClass({ 

render: function(){ 
    return(
     <LC xfield={a} yfield={b} /> 
    ); 
}}); 

React.render(<MyComponent />, document.getElementById('content')); 

我假设A E b是值的阵列。

我的索引页是这样的:

<html> 
    <head> 
    <!-- React --> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.0/react.js"></script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.0/JSXTransformer.js"></script> 
<script src="js/react-chartjs.js"></script> 
<script type="text/jsx;harmony=true" src="MyComponent.js"></script> 

</head> 
<body> 
    <div id="content"></div> 
</body> 

反应,chartjs.js应该是编译chartjs组件。

运行在这样的指数,我有此错误:

Uncaught ReferenceError: LineChart is not defined 

我需要使用此行

var LineChart = require("react-chartjs").Line; 

但MyComponent.js我有需要的错误没有定义

怎么回事?

回答

0

当使用require()时,您正尝试使用通常称为CommonJS的模块系统,并且似乎react-chartjs仅作为CommonJS模块提供。

CommonJS风格的模块加载器被引入并在整个Node.js和IO.js中使用,作为将模块和脚本导入到应用程序的默认方式。

CommonJS现在没有与任何浏览器捆绑在一起,这就是为什么您必须通过如BrowserifyWebpack这样的工具来运行脚本。

0

从安装部分的react-chartjs

This is a CommonJS component only (to be used with something like Webpack or Browserify)

双方的WebPack和Browserfiy使您可以使用require加载模块。似乎react-chartjs被设计为仅与这些工具中的一种一起工作。

+0

OK现在我试试这个: var LineChart = require(“react-chartjs”)。 VAR MyComponent的= React.createClass({ 渲染:函数(){ 返回<应用于LineChart数据= {chartData}选项= {chartOptions}宽度= “600” HEIGHT = “250”/> } });使用此命令: browserify -t reactify main。js -o bundle.js 然后调用bundle.js到index.html它不起作用 }); React.render(,document.body); – ntrax

+0

项目安装页面还说,您必须包含[chart.js](http://www.chartjs.org/)作为依赖项。 –

1

在Node.js的要求模块内置,但在浏览器中,如果你有使用需要,那么你必须使用require.js或只是继承了文件夹中的脚本的HTML部分 <script type="text/jsx" src ="/path/to/the file/"></script>