简体   繁体   English

在 React 中,如何创建字典以根据单个道具更改多个值?

[英]In React, How do I create a dictionary to change multiple values based on a single prop?

I have the following code.我有以下代码。 I know their are multiple ways of doing this and I could make it using conditional return but I would like to know if theres a more efficient way of doing it.我知道他们有多种方法可以做到这一点,我可以使用有条件的回报来做到这一点,但我想知道是否有更有效的方法。

This is my component example这是我的组件示例

export default function APIListThingy({
  title = "List Component",
  type = "dog",
}: {
  title?: string;
  type: "dog" | "cat" | "bunny";
}) {
    

I have "Dog" |我有“狗” | "Cat" | “猫” | "Bunny" to each have a specific set of visual changes (background color, text color), and functional from the API its calling to. “Bunny”对每个人都有一组特定的视觉变化(背景颜色、文本颜色),并且功能从 API 调用到。

What would be the best way to do this?最好的方法是什么?

Edit:编辑:

I have tried the following and works fine.我尝试了以下并且工作正常。

const variables = {
    dog: {
      bg: "#333",
      icon: "dog-outline",
    },
    cat : {
      bg: "#444",
      icon: "cat-outline",
    },
    bunny : {
      bg: "#555",
      icon: "bunny-outline",
    },
  };

and I just call it with我只是用

variables[type]

I'd say it would be simplier to create some generic component let's say Animal, that would accept those style values and apply them.我会说创建一些通用组件(比方说 Animal)会更简单,它会接受这些样式值并应用它们。 Then make your APIListThingy to simply pass props to it like this:然后让你的 APIListThingy 像这样简单地传递道具给它:

<Animal {...variables[type]} />

So you were basically already doing the right thing.所以你基本上已经在做正确的事了。

Your variables object/dictionary works as, so called, "lookup" mapping and imho is a better and more readable alternative to a switch-case您的variables对象/字典作为所谓的“查找”映射工作,恕我直言,它是switch-case的更好、更易读的替代方案

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

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