Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

javascript - Using reactjs with requirejs

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

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

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'));
    }
  });
});

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So I figured it out myself.

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

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"
    ...
  }

  // ...
});

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'));
   ...
});

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'));
   ...
});

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

Hope it helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...