【问题标题】:Cleaner way of conditional Rendering in reactjsreactjs中条件渲染的更简洁方式
【发布时间】:2021-02-25 11:39:17
【问题描述】:

我在 JSX 中使用三元运算符进行这些多项检查,同时在反应中进行条件渲染。一个问题是它必须定义 else 块,在这种情况下我有一个空字符串。这让我很困扰。有没有更好、更清洁的方法?

{order.productClass ? (
                <li style={style.pLocation}>
                  <SettingsInputComponentIcon style={style.rightCardIcon} />
                Product Class :
                  <label
                    style={{
                      marginLeft: 5,
                      color: "gray",
                      fontSize: "16px",
                      fontWeight: "normal",
                    }}
                  >
                    {order.productClass}
                  </label>
                </li>
              ) : (
                  ""
                )}

我的组件中有多个这样的检查,这看起来不干净。

另一种方法是对项目使用 &&。

{order.deliveryTime && (
                <li style={style.pLocation}>
                  <ScheduleIcon style={style.rightCardIcon} />
                Dispatch Time :
                  <label
                    style={{
                      color: "gray",
                      fontSize: "16px",
                      fontWeight: "normal",
                      marginLeft: 5,
                    }}
                  >
                    {order.deliveryTime}
                  </label>
                </li>
              )}

有没有比上述更好、更清洁的方法?

【问题讨论】:

    标签: reactjs jsx


    【解决方案1】:

    你绝对可以使用&amp;&amp;

    Ternary Operator 在您还需要具有 Loading 状态时才有意义。

    If..Else 在有很多移动部件时才有意义。

    另外,尝试使事物模块化。将帮助您组织组件,使内容更具可读性并在一定程度上有助于调试。

    我希望能回答你的问题:)

    【讨论】:

      【解决方案2】:

      我发现这种方式看起来更干净。

      <div style={{ display: order.deliveryTime ? '' : 'none' }}>
      
            <li style={style.pLocation}>
                <ScheduleIcon style={style.rightCardIcon} />
                   Dispatch Time :
                     <label
                       style={{
                            color: "gray",
                            fontSize: "16px",
                            fontWeight: "normal",
                            marginLeft: 5,
                          }}
                       >
                       {order.deliveryTime}
                    </label>
            </li>
      
      </div>
      

      这是使用 css 显示属性。如果有交货时间则显示内容,否则不显示任何内容。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-18
        • 2020-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-22
        相关资源
        最近更新 更多