【问题标题】:How to change a background color based on a variable?如何根据变量更改背景颜色?
【发布时间】:2021-09-23 16:08:21
【问题描述】:

所以我正在调用 PokeAPI 来创建一个 Pokedex,并且我想让它在第一个类型的口袋妖怪是“草”时,例如,背景是绿色,当它是“火”时,背景是红色等。

我最初将其声明为绿色,因为前 3 个神奇宝贝(Bulbasaur、Ivysaur 和 Venusaur)是草类的,我能够创建一个条件将其更改为红色,当类型为火时。我不知道如何在同一样式内为同一参数(背景)创建更多条件。

截至目前,这部分代码如下所示,并且运行良好:(是 styled-components 中的一个组件)

<Background style = {{background: typea === "fire" ? "#ff726f" : ""}}>

我只想添加更多条件,例如:

if typea === "fire" ? "red": ""
if typea === "bug" ? "yellow" : ""
if typea === "poison" ? "purple" : ""

等等

我尝试声明的所有方式都导致了错误。

【问题讨论】:

    标签: javascript reactjs react-native styled-components


    【解决方案1】:

    我只会使用地图:

    const backgrounds = {
        fire: 'red',
        bug: 'yellow',
        poison: 'purple',
    }
    const defaultBackground = 'white';
    
    <Background style = {{background: backgrounds[typea] || defaultBackground }}>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-24
      • 1970-01-01
      • 2016-06-02
      • 2019-06-20
      • 2021-05-10
      相关资源
      最近更新 更多