【问题标题】:Mapping multiple react native components映射多个反应原生组件
【发布时间】:2021-07-30 10:01:21
【问题描述】:

我有多个 react-native 组件(超过 100 个),每个组件都不同。 更准确地说,每个组件实际上都是一个 react-native svg 组件,看起来像这样

import * as React from "react";
import Svg, { Circle, Path } from "react-native-svg";

function SvgAlert(props) {
  return (
    <Svg
      width={24}
      height={24}
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      {...props}
    >
      <Circle cx={12} cy={16.75} r={1.25} fill="#000" />
      <Path fill="#000" d="M11 6h2v8h-2z" />
    </Svg>
  );
}

export default SvgAlert;

我想从我的组件目录中导入所有这些 svgComponents 并在滚动视图中呈现它们

<ScrollView>
  <SvgComp1>
  <SvgComp2>
  .
  .
  <SvgComp100>
<ScrollView>

有什么方法可以映射这些组件或任何其他方法来节省逐个导入每个组件并手动渲染它的繁琐工作(例如组件的映射或其他东西)

<ScrollView>
  {
    components.map(Each=>{
       return <Each/>
      })
  }
<ScrollView>

【问题讨论】:

    标签: reactjs react-native react-component react-native-svg


    【解决方案1】:

    您可以将每个 svg 导入一次,然后重新使用它导入包含所有 svg 的数组。比如:

    AllSvgs.js

    import SVG1 from '...';
    import SVG2 from '...';
    import SVG3 from '...';
    ...
    
    export default SVGsArray = [SVG1, SVG2, SVG3, ...];
    

    然后在一个组件中:

    import SVGsArray from '../path/to/AllSvgs.js';
    ...
    
    <ScrollView>
      {
        SVGsArray.map(Each)=>{
           return <Each/>
      }
    <ScrollView>
    

    【讨论】:

      【解决方案2】:

      我所做的有点不同,我们可以将所有组件导入到一个文件中并以 Object 格式存储,这样我们就可以访问任何你想要的地方,例如 Object

      import A from 'path/to/aComponent';
      import B from 'path/to/bComponent';
      import C from 'path/to/cComponent';
      import D from 'path/to/dComponent';
      
      export const SVGComponents = {
         aComponent: A,
         bComponent: B,
         cComponent: C,
         dComponent: D,
      }
      

      当您尝试渲染时,尝试从对象中读取并渲染它

      import SVGComponents from 'path/to/SVGComponents';
      
      <ScrollView>
          {
              components.map(name)=>{
              return <SVGComponents[name] />
          }
      <ScrollView>
      

      您可以在任何需要的地方存储这些组件,但您确实有常量 NAME

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多