ReactJS and RequireJS -> How to use multiple classes returned from one module?

ε祈祈猫儿з 提交于 2019-12-11 02:49:36

问题


I've got a RequireJS module that returns multiple ReactJS classes that I'd like to be immediately available to the JSX scope.

e.g.

define(["require"], function (require) {

  var SimpleClass = React.createClass({displayName: 'SimpleClass',
    render: function() {
      return <div>HELLO DUDE {this.props.name}</div>;
    }
  });
  var AnotherSimpleClass = React.createClass({displayName: 'AnotherSimpleClass',
    render: function() {
      return <div>SUPER DUDE {this.props.name}</div>;
    }
  });


  var result = 
  {
    AnotherSimpleClass: AnotherSimpleClass,
    SimpleClass: SimpleClass
  };

  return result;
});

I'd like to be able to use these in React/JSX like so (pseudocode):

define(["require","jsx!app/my_classes"], function (require, MyClasses) {

  React.renderComponent(
    <div>
      <MyClasses.SimpleClass name="Test" />
      <MyClasses.AnotherSimpleClass name="John" />
    </div>
  , this.el);

});

when I do, React fails to find my module classes. It only works if I expose the classes to the scope, ie:

define(["require","jsx!app/my_classes"], function (require, MyClasses) {

  var SimpleClass = MyClasses.SimpleClass;
  var AnotherSimpleClass = MyClasses.AnotherSimpleClass;

  React.renderComponent(
    <div>
      <SimpleClass name="Test" />
      <AnotherSimpleClass name="John" />
    </div>
  , this.el);

});

How can I do this? I know I can extract them to the current scope one by one, or extract them to the global scope, but it seems I should be able to use them from JSX without modification. Thanks!

Note that I know I could just expose them to the global scope with a function like so:

  function exposeClasses(obj){
    for (var prop in obj)
    {
      window[prop] = obj[prop];
    }
  }

  exposeClasses(MyClasses);

but I'd prefer to leave them in their namespaces if possible. Note that this is similar to this question being asked here on StackOverflow


回答1:


This is now supported in ReactJS, as this pull request to add this feature has been merged.



来源:https://stackoverflow.com/questions/23739166/reactjs-and-requirejs-how-to-use-multiple-classes-returned-from-one-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!