如何在地图return内使用if?

How to use if within a map return?

我需要根据数据模型生成不同的 reactJS 代码,但我得到

In file "~/Scripts/Grid.jsx": Parse Error: Line 13: Unexpected token if (at line 13 column 15) Line: 52 Column:3

使用此代码

var GridRow = React.createClass({
    render: function() {
        var row;

        row = this.props.cells.map(function(cell, i) {
            return (
                if(cell.URL != null && cell.URL.length > 0){
                    <td className={cell.Meta.HTMLClass} key={i}>{cell.Text}</td>        
                }
                else {
                    <td className={cell.Meta.HTMLClass} key={i}>{cell.Text}</td>
                }
            );
        }.bind(this));

        return (
            <tr>
                {row}
            </tr>
        );
    }
});

render 部分的使用方式好像真的很有限?

您将 return 语句放在 if 子句中,如下所示:

    row = this.props.cells.map(function(cell, i) {

        if(cell.URL != null && cell.URL.length > 0){
            return <td className={cell.Meta.HTMLClass} key={i}>{cell.Text}</td>;        
        }
        else {
            return <td className={cell.Meta.HTMLClass} key={i}>{cell.Text}</td>;
        }

    }.bind(this));

您还可以使用 ternary(内联 if/else)语句。它可能看起来像这样:

row = this.props.cells.map(function(cell, i) {
    return (cell.URL != null && cell.URL.length > 0) ? 
        (<td className={cell.Meta.HTMLClass} key={i}>{cell.Text}</td>) :
        (<td className={cell.Meta.HTMLClass} key={i}>{cell.Text}</td>)
}.bind(this));

或 es6

row = this.props.cells.map((cell, i) => (cell.URL != null && cell.URL.length > 0) ? 
        (<td className={cell.Meta.HTMLClass} key={i}>{cell.Text}</td>) :
        (<td className={cell.Meta.HTMLClass} key={i}>{cell.Text}</td>)
);

但是,为了便于阅读,我建议使用 nilgun 的答案。

虽然我会删除 else 语句,因为它是多余的。您也可以删除大括号,这是一个偏好问题。

row = this.props.cells.map(function(cell, i) {
    if(cell.URL != null && cell.URL.length > 0)
        return <td className={cell.Meta.HTMLClass} key={i}>{cell.Text}</td>;        
    return <td className={cell.Meta.HTMLClass} key={i}>{cell.Text}</td>;
}.bind(this));