简体   繁体   中英

Organizing React Components

I am building a React App which consists of lot of smaller components. At present I am importing the components in app.js like this:

import Nav from './components/nav'
import ColorPicker from './components/colorPicker'

class App extends Component {
  render() {
    return (
      <div>
      <Nav />
      <ColorPicker />
      </div>
    );
  }
}

export default App;

Each component is a separate js file (nav.js, colorPicker.js). Is there anyway to just import everything in components folder so I don't have to explicitly specify importing of the components.

I'm not sure if there is a way to just import everything from a folder with one module per file, but you can make a kind of index.js file in which you would import everything that you will want, then:

  export * from nav;
  export * from colorPicker;

And then you only have to import your one index file from which you can: import {nav, colorPicker} from './components/things';

You always have to explicitly set the import of the components you use, but what you can do is decrease the amount of code typed by setting up an index file where you export all components you want to make available in said file, like this for example:

./components/index.js

import Component1 from './Component1';
import Component2 from './Component2';
import Component3 from './Component3';

export {
  Component1,
  Component2,
  Component3,
};

Then import the needed components in the desired file like this:

./app.js

import { Component1, Component2 } from './components';

class App extends Component {
  render() {
    return (
      <div>
      <Nav />
      <ColorPicker />
      </div>
    );
  }
}

export default App;

Tree structure

app.js
components
+---
    Component1.js
    Component2.js
    index.js

If you can add a babel plugin, you can use babel-plugin-wildcard , that is a plugin that makes exactly what you want.

Taken from NPM:

With the following folder structure:

|- index.js
|- dir
    |- a.js
    |- b.js
    |- c.js

the following JS:

import * as Items from './dir';

will be compiled to:

const Items = {};
import _wcImport from "./dir/a";
Items.A = _wcImport;
import _wcImport1 from "./dir/b";
Items.B = _wcImport1;
import _wcImport2 from "./dir/c";
Items.C = _wcImport2;

meaning you will be able to access the items using Items.A and Items.B.

You can also selectively choose files using:

import { A, C } from "dir/*";

which in the above example would convert to:

import A from "./dir/a";
import C from "./dir/c";

The above is like doing:

import * as temp from "dir";
const { A, C } = temp;

Answer found inside this post .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM