如何在 JSX 中的三元运算符中调用两个函数?
How to have two function calls inside ternary operator in JSX?
如果在三元运算符中满足条件,我将尝试渲染两个组件。但是,只有第二个组件被渲染。我怎么可能在条件之后放置两个函数调用?
{
views === "monthly"
? this.renderDays(),
this.renderCells()
: null
}
我尝试了以下方法(none 有效)
{
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');
您可以 return 组件数组:
{
views === "monthly"
? [this.renderDays(), this.renderCells()]
: null
}
或者如果方法 return 数组本身,只需展开它们:
{
views === "monthly"
? [...this.renderDays(), ...this.renderCells()]
: null
}
您可以很容易地将括号中的两个函数结合起来,然后借助逗号将它们分开,然后很容易调用它们。
它们将在内部仅被视为函数调用。
您可以使用逗号分隔表达式并将其包装在带有括号的单个语句中作为三元组。
{ views === "monthly" ? (this.renderDays(), this.renderCells()): null }
参考:
如果在三元运算符中满足条件,我将尝试渲染两个组件。但是,只有第二个组件被渲染。我怎么可能在条件之后放置两个函数调用?
{
views === "monthly"
? this.renderDays(),
this.renderCells()
: null
}
我尝试了以下方法(none 有效)
{
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');
您可以 return 组件数组:
{
views === "monthly"
? [this.renderDays(), this.renderCells()]
: null
}
或者如果方法 return 数组本身,只需展开它们:
{
views === "monthly"
? [...this.renderDays(), ...this.renderCells()]
: null
}
您可以很容易地将括号中的两个函数结合起来,然后借助逗号将它们分开,然后很容易调用它们。
它们将在内部仅被视为函数调用。
您可以使用逗号分隔表达式并将其包装在带有括号的单个语句中作为三元组。
{ views === "monthly" ? (this.renderDays(), this.renderCells()): null }
参考: