【问题标题】:How to use if within a map return?如果在地图返回中如何使用?
【发布时间】:2015-04-18 12:08:28
【问题描述】:

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

在文件“~/Scripts/Grid.jsx”中:解析错误:第 13 行:意外标记 如果(在第 13 行第 15 列)行:52 列: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 js 一点也不专业,但在我看来它并没有完全重写 javascript:在 return 语句中可能找不到 if 语句
  • 似乎在这两种情况下,您的 if-else 都会创建相同的

标签: javascript reactjs react-jsx


【解决方案1】:

您将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));

【讨论】:

  • 你能解释一下为什么if语句不能写在return里面吗?
  • @Chrisk8er 好吧,它在 js 和 jsx 中都不是有效的语法。
  • @Chrisk8er 是的,它是有效的 javascript,并且一直在 JSX 中使用。请参阅下面有关如何使用三元语句的答案
  • 由于某种原因这对我不起作用 - else 语句似乎永远不会触发
【解决方案2】:

您也可以使用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));

【讨论】:

  • 嗨@S.Kiers,在 e6 示例中,我们如何执行 else if?
  • 你说的是三元例子?如果您需要 else if,我建议您使用完整的 if/elseif/else 块。三元运算符通常只是语法糖。但是,如果您需要,您可以“嵌套”三元运算符(例如,在反应中您可以这样做,但不要这样做!):condition1 ? "This is the IF" : condition2 ? "This is the ELSE IF" : "This is the ELSE"
猜你喜欢
  • 1970-01-01
  • 2013-10-12
  • 2015-05-14
  • 1970-01-01
  • 2013-11-25
  • 1970-01-01
  • 2018-08-04
  • 1970-01-01
  • 2012-12-06
相关资源
最近更新 更多