【问题标题】:Conditionally rendering part of component in elixir在 Elixir 中有条件地渲染部分组件
【发布时间】:2021-06-30 04:46:34
【问题描述】:

我是 elixir 新手,无法以 DRY 方式渲染此组件。我有这个 CardHeader 组件

    <CardHeader
      :if={{ not is_nil(@truck_load.sand_type) }}
      background_color={{ @truck_load.sand_type_background_color }}
      text_color={{ @truck_load.sand_type_text_color }}
      title={{ @truck_load.sand_type }}
      :if={{ not is_nil(@truck_load.measured_weight) }}
      info={{"#{@truck_load.measured_weight} lb (#{
      Weight.convert_pounds_to_tons_and_round(@truck_load.measured_weight, 2)
      } tons)"}}
    />

可能有也可能没有@truck_load.measured_weight 值。如果是这样,我希望将 info 变量设置为其值,并使用字符串插值来显示测量单位。 如果没有 @truck_load.measured_weight 值,我不希望出现测量单位,所以我希望将 info 设置为空字符串。

如果没有单独的 CardHeader 组件来检查 @truck_load.measured_weight 是否像这样,我无法弄清楚如何让它工作:

<CardHeader
          :if={{ not is_nil(@truck_load.sand_type) }}
          background_color={{ @truck_load.sand_type_background_color }}
          text_color={{ @truck_load.sand_type_text_color }}
          title={{ @truck_load.sand_type }}
          :if={{ is_nil(@truck_load.measured_weight) }}
          info=""
        />

有没有更好、更干燥的方法来做到这一点?

谢谢!!

【问题讨论】:

  • 为什么不在服务器端执行这些检查,并相应地设置info 变量?

标签: html elixir phoenix-framework elixir-iex phoenix-live-view


【解决方案1】:

只需分成 2 个组件,例如

    <SandType
      background_color={{ @truck_load.sand_type_background_color }}
      text_color={{ @truck_load.sand_type_text_color }}
      title={{ @truck_load.sand_type }}
    />

    <WeightType
      info={{"#{@truck_load.measured_weight} lb (#{
      Weight.convert_pounds_to_tons_and_round(@truck_load.measured_weight, 2)
      } tons)"}}
    />
    <CardHeader>
      <SandType :if={{ not is_nil(@truck_load.sand_type) }} />
      <WeightType :if={{ not is_nil(@truck_load.measured_weight) }} />
    </CardHeader>

【讨论】:

    猜你喜欢
    • 2015-05-16
    • 1970-01-01
    • 2022-07-23
    • 2018-09-13
    • 2019-02-18
    • 1970-01-01
    • 2013-10-11
    • 1970-01-01
    • 2018-12-20
    相关资源
    最近更新 更多