遍历组件并返回切换案例(React.js) [英] Loop through components and return in switch case (React.js)

查看:139
本文介绍了遍历组件并返回切换案例(React.js)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢 svg-to-react-cli 脚本我的图标有73个组件. 现在,如果要调用这些图标,则可以分别调用要使用的每个图标. 但这不是我想要的.

我想要的是仅调用一个组件,在其中添加名称"值.
例如:< Icon name ='我要调用的73个组件之一的名称'/>

So thanks to the svg-to-react-cli script I have 73 components for my icons. Now, if I want to call these icons, I can individually call each one I want to use. But this is not what I want.

What I want is to call only one component where I add a 'name' value to.
e.g.: < Icon name='Name of one of the 73 components I wish to call' />

如何遍历目录中的多个组件,并在开关盒中返回它们?

这是我目录中所有73个组件的样子

How do I loop through multiple components inside a directory, and return them inside a switch case?

This is how all my 73 components inside the directory look like

import React from 'react';

export default function NAMEOFICON(props) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width={100} height={100} {...props}>
      ...CONTENT OF SVG...
    </svg>
  );
}

这就是我所拥有的

import React from 'react';
import ALLCOMPONENTS from 'DIRECTORY WITH COMPONENTS'

// HERE I WANT TO LOOP THROUGH COMPONENTS AND ADD THEM IN THIS SWITCH
const getPath = (name, props) => {
  switch (name) {
    case 'NAME OF THE COMPONENT':
      ... HERE COMES CONTENT OF COMPONENT...
    default:
      return <path />;
  }
};
// HERE I CREATE A CONST TO LATER CALL THE DESIRED COMPONENT BY NAME
const Icon = ({
  name = '',
  style = {},
  fill = 'currentColor',
  viewBox = '',
  width = '20px',
  className = 'icon icon' + name,
  height = '20px'
}) => (
    {NAME OF COMPONENT({ fill })}
);

export default Icon ;

推荐答案

依赖客户端脚本中的目录内容是不正确的,因为捆绑的应用程序中没有目录内容.

It's incorrect to rely on directory contents in client-side script because there's none in bundled application.

正确的方法是拥有一个桶"模块,以重新导出所有子模块:

A proper way is to have a 'barrel' module that re-exports all submodules:

icon-components/index.js

export { default as FooIcon } from './foo-icon';
export { default as BarIcon } from './bar-icon';

并像这样使用它:

import * as icons from './icon-components';

...

for (const [iconComponentName, IconComponent] of Object.entries(icons)) { ... }

生成index.js与生成图标组件的方式类似是有意义的,即在可以访问文件系统的Node.js环境中. svg-to-react-cli可以为此目的而被分叉,或者可以是一个单独的脚本.

It makes sense to generate index.js similarly to how icon components were generated, i.e. in Node.js environment where there's an access to file system. svg-to-react-cli could be forked for this purpose, or this could be a separate script.

这篇关于遍历组件并返回切换案例(React.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆