【问题标题】:How to render conditional HTML elements in React如何在 React 中渲染条件 HTML 元素
【发布时间】:2021-05-01 03:43:43
【问题描述】:

以下代码有什么问题?我尝试了link 中给出的许多选项。

  { 
      !hideCurrentLocation && (
        {currentLocation?.city}
        {currentLocation?.city && ', '}
        {currentLocation?.country_code2}
      )
  }

{currentLocation?.city} 行出现错误提示需要逗号。

【问题讨论】:

    标签: javascript html reactjs jsx


    【解决方案1】:

    括号太多。此外,如果您尝试呈现“城市、国家/地区代码”,则需要为有效的 JSX 返回单个节点。我建议将城市和国家代码转储到一个数组中,然后将它们连接成一个字符串。

    {!hideCurrentLocation && (
      <>
        {[currentLocation?.city, currentLocation?.country_code2]
          .filter(Boolean)
          .join(", ")}
      </>
    )}
    

    【讨论】:

    • 谢谢解答,现在没有错误了。但是当 !hideCurrentLocation == true 时,它​​不会打印城市和国家/地区代码。两者都是字符串,但被转换为布尔值。
    • @UmairJameel 哎呀,要过滤数组,抱歉。 .filter(Boolean) 将过滤掉虚假值,只留下定义的 citycountry_code2 一起加入。
    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2019-08-31
    • 2022-12-10
    • 2017-08-18
    • 2021-11-20
    • 2022-01-11
    • 1970-01-01
    相关资源
    最近更新 更多