简体   繁体   English

反应 + 打字稿。 根据动态道具值渲染正确的图标

[英]React + Typescript. Render proper Icon based on dynamic props value

I have a span in my JSX in which I want to render a proper icon based on the dynamic props value我的 JSX 中有一个跨度,我想在其中根据动态道具值呈现适当的图标

<span>{IconToProductMap(value)}</span>

This is how this function looks like这就是这个函数的样子

const IconToProductMap = (value: string) => {
  if (value === 'sampleValue') {
    return <Icon type={IconType.card} />
  }
  if (value === 'sampleValue2') {
    return <Icon type={IconType.card2} />
  }
  return <Icon type={IconType.card3} />
}

This solution is really bad and I'd like to be able to dynamically assign the value so that I can render the icon like this这个解决方案真的很糟糕,我希望能够动态分配值,以便我可以像这样呈现图标

    <span>{IconToProductMap[value]}</span>

To achieve that I've created the mapper object为了实现这一点,我创建了映射器对象

const mapper = {
  possiblePropsValue1: IconType.card,
  possiblePropsValue2: IconType.bag,
  possiblePropsValue3: IconType.arrow_left,
}

and used it like so:并像这样使用它:

    <span>{mapper[value]}</span>

The problem is that TS throws问题是TS抛出

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ possiblePropsValue1: IconType;元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{ possiblePropsValue1: IconType; possiblePropsValue2: IconType; possiblePropsValue2:图标类型; possiblePropsValue3: IconType; possiblePropsValue3:图标类型; }'. }'。 No index signature with a parameter of type 'string' was found on type '{ possiblePropsValue1: IconType;在类型 '{ possiblePropsValue1: IconType; 上找不到具有类型参数的索引签名。 possiblePropsValue2: IconType; possiblePropsValue2:图标类型; possiblePropsValue3: IconType; possiblePropsValue3:图标类型; }' }'

Could someone explain me how to properly fix that?有人可以解释一下如何正确解决这个问题吗?

You should define mapper with a proper type您应该使用适当的类型定义mapper

const mapper: Record<string, JSX.Element> = {
  possiblePropsValue1: IconType.card,
  possiblePropsValue2: IconType.bag,
  possiblePropsValue3: IconType.arrow_left,
}

Record<key,value> receives key as string, value as JSX.Element which is from your IconType returned value. Record<key,value>以字符串形式接收key ,以JSX.Element形式接收value ,它来自您的IconType返回值。

You can use an enum to simplify string parameters & better manage the icon types.您可以使用枚举来简化字符串参数并更好地管理图标类型。 You can store the strings ( sampleValue ) in the enum.您可以将字符串 ( sampleValue ) 存储在枚举中。

enum IconType {
  card = "card",
  bag = "bag",
  arrow_left = "arrow_left"
}

interface IconProps {
  iconType: IconType;
}

const Icon = (props: IconProps) => {
  const { iconType } = props;
  return <div>{iconType}</div>; // just for demonstration
};

export default function App() {

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Icon iconType={IconType.bag} />
    </div>
  );
}

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

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