Multiple React components in a single module
I am new to the whole browserify thing. I have been trying to use browserify + reactify + gulp to transform, minify and combine a React application. As long as I have a single React.createClass
with a single module.exports = MyComponent
everything works fine. Since I have several shared components I physically host in the same file and reuse across projects, I would like to export more than one component. I have tried an array:
module.exports = [Component1, Component2]
and have also tried an object with multiple properties:
module.exports = {Comp1: Componenet1, Comp2: Component2}
and have also tried in-lining the calls to createClass
in the object, but that didn't help.
Is there a way to do this or do I have to split every component in to a seperate JSX file?
I have put multiple components in one file and export the object like you suggested.
module.exports = {
comp1: Component1,
comp2: Component2
}
Then where they are used do
var comp1 = require('your/path/to/components').comp1;
var comp2 = require('your/path/to/components').comp2;
You can do like this, with an index.js file into your /components/
folder
/components/index.js
import Users from './Users/Users';
import User from './Users/User';
module.exports = {
User,
Users
}
IMPORT
import { Users, User } from './components';
As you can see, I named my file index.js , it prevent me from write it in the import declaration. If you want to name your file with another name than index.js , you'd have to write the name of the file in the import, Node won't guess it ! ^^
I use function to return component.
module.exports = {
comp1: function(){
return Component1;
}
}
Then
var myCompontents = require('./components');
var comp1 = myComponents.comp1();
链接地址: http://www.djcxy.com/p/52104.html
上一篇: handleClick不起作用
下一篇: 单个模块中有多个React组件