使用reactjs和requirejs [英] Using reactjs with requirejs

查看:124
本文介绍了使用reactjs和requirejs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我开始使用 reactjs 以及 backbonejs 路由器来构建应用程序。

Recently, I started using reactjs along with a backbonejs router to build an application.

我通常使用 requirejs 进行依赖和代码管理。但是,当我尝试包含包含 jsx 语法的文件时出现问题。

I usually use use requirejs for dependency and code management. But, problem arises when I try to include files that contain jsx syntax.

这是我到目前为止所拥有的作为我的 router.js

This is what I have so far as my router.js:

define(["backbone", "react"], function(Backbone, React) {

  var IndexComponent = React.createClass({
    render : function() {
      return (
        <div>
        Some Stuff goes here
        </div>
        );
    }
  });



  return Backbone.Router.extend({
    routes : {
      "": "index"
    },
    index : function() {
      React.renderComponent(<IndexComponent />, document.getElementById('index'));
    }
  });
});

如何将IndexComponent放在自己的文件中并在此文件中调用它?我已经尝试了通常的方法(与骨干和反应一样)但由于 jsx 语法而出现错误。

How do I put IndexComponent in its own file and call it in this file ? I have tried the usual method (the same that I have used with backbone and react) but got an error due to jsx syntax.

推荐答案

所以我自己弄清楚了。

我从这个仓库得到了必要的文件和说明: jsx-requirejs-plugin

I got the necessary files and instructions from this repo: jsx-requirejs-plugin.

一旦我 jsx插件 JSXTransformer ,我按照存储库中的说明更改了我的代码:

Once I had jsx plugin and modified version of JSXTransformer, I changed my code as instructed in the repository :

require.config({
  // ...

  paths: {
    "react": "path/to/react",
    "JSXTransformer": "path/to/JSXTransformer",
    "jsx": "path/to/jsx plugin"
    ...
  }

  // ...
});

然后,我可以通过 jsx引用JSX文件!插件语法。例如,要加载组件目录中的Timer.jsx文件:

Then, I could reference JSX files via the jsx! plugin syntax. For example, to load the Timer.jsx file that is in a components directory:

require(['react', 'jsx!components/Timer'], function (React, Timer) {
   ...
   React.renderComponent(<Timer />, document.getElementById('timer'));
   ...
});

我还可以访问 .js 个文件使用相同的代码使用 jsx 语法:

I could also access .js files that had jsx syntax in them using the same code:

require(['react', 'jsx!components/Timer'], function (React, Timer) {
   ...
   React.renderComponent(<Timer />, document.getElementById('timer'));
   ...
});

此外,我不需要输入 / ** @jsx React。 DOM * / 位于使用 jsx 语法的文件顶部。

Also, I did not need to put /** @jsx React.DOM */ at the top of files using jsx syntax.

希望它有帮助。

这篇关于使用reactjs和requirejs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆