Multiple React components in a single module

雨燕双飞 提交于 2019-11-28 06:54:27

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();

You can simply export multiple components as an array:

module.exports = [Component1, Component2]

Then to use the components:

var MyComponents = require('your/path/to/components');
var Component1 = MyComponents[0];
var Component2 = MyComponents[1];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!