简体   繁体   English

基于数组的 React 组件映射

[英]React component map based on an array

I dynamically create an element based on passed ID:我根据传递的 ID 动态创建一个元素:

const Icon: FC<IconPropsI> = ({iconId, ...rest}) => {
  const iconsMap: IconsMapT = {
    IconUser: IconUser,
    IconTime: IconTime,
    IconVideo: IconVideo
  }

  return createElement(iconsMap[iconId], rest)
}

Value of each map property has corresponding functional component.每个地图属性的值都有相应的功能组件。

I would like to avoid repeating myself.我想避免重复自己。 I have created a list of IDs instead.我已经创建了一个 ID 列表。 With the following array...使用以下数组...

export const IconsIds: IconsIdsT = [ 'IconUser', 'IconTime', 'IconVideo', 'manymore...']

...how can I create the map dynamically inside the Icon component, so I don't have to write 200+ different icon IDs three times? ...如何在Icon组件内动态创建地图,这样我就不必写 3 次 200 多个不同的图标 ID?

In iconsMap you could also use property shorthand to not repeat yourself.iconsMap您还可以使用属性速记来避免重复。

So instead of const iconsMap = { IconUser: IconUser } you should be able to do something like const iconsMap = { IconUser, ...otherIcons }所以代替const iconsMap = { IconUser: IconUser }你应该能够做类似const iconsMap = { IconUser, ...otherIcons }

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#property_definitions请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#property_definitions

Alternatively, there's a babel plugin that can compose all exports from a certain folder to a single object, and then you can get values from this object.或者,有一个babel插件可以将某个文件夹中的所有导出组合到一个对象中,然后您可以从该对象中获取值。

Check this answer检查这个答案

But please, be aware of potential issues - if you will pass wrong iconId , or if your bundler expects all imports being statically defined(AFAIK - at least react-native and expo expects that) - you might face issues with such an approach, and manual map typing might be more resilient solution.但是请注意潜在的问题 - 如果您将传递错误的iconId ,或者您的iconId希望所有导入都是静态定义的(AFAIK - 至少react-nativeexpo期望) - 您可能会遇到这种方法的问题,并且手动地图输入可能是更具弹性的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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