将React组件导出为数组的最干净方法是什么?

时间:2020-03-05 17:36:50

标签: javascript reactjs ecmascript-6

此代码有效,但是我想知道是否有一种方法可以清理它。

我正在制作SVG模式库,并希望创建一个仪表板来列出每个模式,与this site非常相似。每个模式都是一个React组件,我将从index.js文件中将它们导出为数组:

import FirstPattern from "./FirstPattern";
import SecondPattern from "./SecondPattern";
import ThirdPattern from "./ThirdPattern";
import FourthPattern from "./FourthPattern";
import FifthPattern from "./FifthPattern";
import SixthPattern from "./SixthPattern";
// ...and about 100 more...

export default [
  FirstPattern, 
  SecondPattern, 
  ThirdPattern,
  FourthPattern,
  FifthPattern,
  SixthPattern,
  // ...and about 100 more...
];

这使我可以在仪表板上通过它们进行映射:

import patterns from "./patterns";

function PatternDashboard() {
  const [color, setColor] = useState("#ff0000");
  const [background, setBackground] = useState("#000000");

  return (
    <>
      {patterns.map((Pattern, id) => (
        <Pattern
          key={`icon${id}`}
          color={color}
          background={background}
        />
      ))}
    </>
  )
}

是否有一种更干净的方法来构造我的index.js文件,因此它没有那么重复?

1 个答案:

答案 0 :(得分:1)

不愿做一个数组只是为了考虑做一个import * as patterns from './patterns',然后您就不必在索引文件中将它们列出两次:

export { default as FirstPattern } from './FirstPattern';
export { default as SecondPattern } from './SecondPattern';
...
import * as patterns from './patterns';

Object.keys(patterns).... // (or Object.values/Object.entries)

(评论太久了,我知道这不是答案)。