首页 > 解决方案 > React:通过对象映射值以返回 SVG

问题描述

我正在尝试从父组件(呈现标签)传递一个值,并希望很快将一个图标向下传递到我的CountryFlag组件中。

到目前为止,它是这样通过的:

<CountryFlag
   countryCode={option.code} 
/>

option.code返回一个国家代码,例如“AFN”。

然后,我想将该 countryCode 放入我的 CountryFlag 组件并映射到我的CountryMap数组,以便例如,如果从父组件传递“AFN”,我将能够返回“Afghan”SVG 作为渲染的 FlagComponent 的一部分.

我知道我离最终的实施还有一点距离,但任何关于我下一步可能去哪里的建议都会非常感激。

import Afghanistan from "./CountryFlags/Afghanistan.svg";
import Albania from "./CountryFlags/Albania.svg"

import styled from "styled-components";

const countryMap = {
  AFN: {
    countryCode: "AFN",
    name: "afghanistan",
    icon: Afghanistan,
  },
  ALL: {
    countryCode: "ALL", 
    name: "albania",
    icon: Albania,
  },
};

const StyledImage = styled.div`
  height: 32px;
  width: 32px;
`;

const CountryFlag = ({className, code="" }: Props) => {
  const FlagComponent = countryMap[code];

  if (!FlagComponent) {
    console.warn(`icon for ${code} is not valid`);
    return null;
  }
  return (
    <StyledImage>
      <FlagComponent>
        src={}
      </FlagComponent>
    </StyledImage>
  );
}

export default CountryFlag;

标签: javascriptreactjs

解决方案


推荐阅读