繁体   English   中英

如何在JSX中的三元运算符中进行两个函数调用?

[英]How to have two function calls inside ternary operator in JSX?

如果在三元运算符内满足条件,我试图渲染两个组件。 但是,仅渲染第二个组件。 我怎么可能在条件之后放两个函数调用?

    {
      views === "monthly"
      ? this.renderDays(),
        this.renderCells()
      : null
    }

我尝试了以下(没有一个工作)

    {
      views === "monthly"
      ? this.renderDays(),
        this.renderCells()
      : null
    }

    {
      views === "monthly"
      ? (this.renderDays(), this.renderCells())
      : null
    }

    {
      views === "monthly"
      ? (this.renderDays(); this.renderCells())
      : null
    }

您可以返回一组组件:

{
  views === "monthly"
  ? [this.renderDays(), this.renderCells()]
  : null
}

或者,如果方法返回数组本身,只需传播它们:

 {
  views === "monthly"
  ? [...this.renderDays(), ...this.renderCells()]
  : null
}

您可以使用逗号分隔表达式,并将其包含在带有三元括号的单个语句中。

{  views === "monthly"  ? (this.renderDays(), this.renderCells()): null   }

参考: 如何在三元运算的结果上执行多个函数?

将函数包装在括号内,因为如果你使用逗号分隔函数调用 - this.renderDays(),this.renderCells()那么它会在三元条件允许时抛出语法错误? 并且: 因此,使用括号来包装多个函数调用:

 function renderDays(){ console.log('renderDays') } function renderCells(){ console.log('renderCells') } 1 == 1? (renderDays(), renderCells()): console.log('False'); 

您可以轻松地将两个函数组合在一个parathesis中,然后在逗号的帮助下将它们分开,然后轻松地调用它们。

它们将在内部被视为函数调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM