问题
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