【问题标题】:Conditionally render <a href> if map value equals specific text [duplicate]如果地图值等于特定文本,则有条件地呈现 <a href> [重复]
【发布时间】:2020-06-07 16:40:32
【问题描述】:

我正在根据地图(列标题)的地图(数据)呈现表格。我无法在 item[col.property] 之前添加 if 条件,因为它会返回意外的值错误。

如果 col.heading 等于“specifiedHeader”,我将如何有条件地呈现一个 &lt;a href&gt;,并将返回的 item[col.property] 值作为 href 值。

我假设 if 条件逻辑是,但我弄错了位置:

{if (col.heading == 'specifiedHeader') {
   <td><a href={item[col.property]}/></td>
   }
else {
   <td>{item[col.property]}</td>
   }
}

常量表:

  const Table = ({ columns, data }) => (
    <table className="table">
      <thead>
        <tr>
          {columns.map(col => (
            <th key={`header-${col.heading}`}>{col.heading}</th>
          ))}
        </tr>
      </thead>
      <tbody>
        {data.map(item => (
          <tr>
            {
              columns.map(
                col => (
                  <td>
                    {
                      item[col.property]
                    }
                  </td>
                ))
            }
          </tr>
        ))}
      </tbody>
    </table>
  );

【问题讨论】:

  • 是的,您可以将其标记为重复并与该问题相关。

标签: javascript reactjs iterator


【解决方案1】:

试试这个:

{col.heading === 'specifiedHeader' &&
  <td><a href={item[col.property]}/></td>
}{ col.heading !== 'specifiedHeader' &&
   <td>{item[col.property]}</td>
}

【讨论】:

    【解决方案2】:

    您可以使用三元运算符:https://reactjs.org/docs/conditional-rendering.html#inline-if-else-with-conditional-operator

    {
        col.heading === 'specifiedHeader' ? (
            <td><a href={item[col.property]}/></td> 
        ) : (
            <td>{item[col.property]}</td>
        )
    }
    

    【讨论】:

      【解决方案3】:

      用这个替换你的第二个columns.map

      columns.map(
        col => (
          <td>
            {
              col.heading === 'specifiedHeader'
                ? item[col.property]
                : <a href={item[col.property]}/>
            }
          </td>
        ))
      

      【讨论】:

        猜你喜欢
        • 2021-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-17
        • 2014-04-02
        • 2020-03-21
        • 2019-09-05
        • 1970-01-01
        相关资源
        最近更新 更多