javascript - React/Javascript If 语句在 map 内

标签 javascript reactjs

我正在尝试制作一个表格,该表格将根据从 map 函数派生的属性具有不同颜色的行:

       var tableData = this.state.data.map(attribute =>

            {if(attribute.duplicate.toString()== "true")
                return <tr className="table-success">;
            else
                return <tr className="table-warning">;
            }
                <td> {count++} </td>
                ...
                <td> {attribute.duplicate.toString()} </td>
            </tr>
       );

现在 var tableData 被传递到实际的表:

<div>
        <div>
            <table className="table">
                <tr className="thead-inverse">
                    <th> # </th>
                    ...
                    <th> duplicate </th>
                </tr>
                    {tableData}
            </table>

        </div>
    </div>

但我收到以下错误:

[INFO] Module build failed: SyntaxError: C:/Users/.../all.js: Unterminated JSX contents (78:14)
[INFO] 
[INFO]   76 | 
[INFO]   77 |             </div>
[INFO] > 78 |         </div>
[INFO]      |               ^

你知道问题是什么,或者有其他方法来实现我想要做的事情吗?

最佳答案

只需将条件逻辑移至 className 内或将其分配给变量,然后在 tr 内使用它。

   var tableData = this.state.data.map(attribute => 
       <tr className={attribute.duplicate.toString() == "true" ? "table-success" : "table-warning"}>
            <td> {count++} </td>
            ...
            <td> {attribute.duplicate.toString()} </td>
        </tr>
   );

关于javascript - React/Javascript If 语句在 map 内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48064791/

相关文章:

twitter-bootstrap - React Material UI - Bootstrap 容器等效项

node.js - 使用 babel 将 JSX 转换为 JS

javascript - 如何在 Visual Studio Code 中使用 TypeScript 和 JavaScript 禁用自动导入的自动分号?

javascript - 停止传播和开始传播

javascript - 实现 Promise.all 和 Promise.settle 的混合

python - 导入 "rest_framework"无法解析。但是我已经安装了djangorestframework,不知道哪里出了问题

javascript - 基于像素距离的水平滚动事件

javascript - 用卡片实现 Vue 可拖动?

reactjs - 创建具有远程排序、分页、过滤功能的表

javascript - 如何在 React.js 中使用 id 卸载循环生成的 div?