正确的语法我有一个布尔值,道具的反应,我想使用它,如下图所示:阵营:什么是布尔检查
const MyComponent = ({ prop1, prop2, isBoolean }) => {
...do something..
return (
if (isBoolean) ? (do this) : (do that)
}
,所以我说,如果isBoolean为真,那么这样做别的去做。这是正确的语法吗?
正确的语法我有一个布尔值,道具的反应,我想使用它,如下图所示:阵营:什么是布尔检查
const MyComponent = ({ prop1, prop2, isBoolean }) => {
...do something..
return (
if (isBoolean) ? (do this) : (do that)
}
,所以我说,如果isBoolean为真,那么这样做别的去做。这是正确的语法吗?
如果要使用三元运算符,则必须删除if
关键字。
isBoolean ? (do this) : (do that)
然后它确实是一个合适的语法。
不,它不是在JS正确的语法。您在一个声明中混合使用了if
声明和tenary operator。正确的语法可以是:
如果声明
if (isBoolean) {
//do this
} else {
//do that
}
或tenary操作
isBoolean ? expression1 : expression2;
没有,要么干脆:
isBoolean ? this : that
或者,对于更复杂的(多线)代码:
if (isBoolean) {
this
} else {
that
}
如果你想要做的return (expression)
,你将需要使用三元操作符内部条件呈现。
const MyComponent = ({ prop1, prop2, isBoolean }) => {
// ...do something..
return (
{ isBoolean ? (do this) : (do that) }
);
};
你也可以return语句之前执行的条件如下:
const MyComponent = ({ prop1, prop2, isBoolean }) => {
// ...do something..
const DOMToRender = isBoolean ? this : that;
return (
{ isBoolean ? (do this) : (do that) }
);
};
你也可以用和if/else语句repleace const DOMToRender = isBoolean ? this : that;
。
如果有可能在任何时候都未定义(即默认情况下),您可以通过双重砰砰声将它强制为三元组的布尔值!
return !!isBoolean ? (do this) : (do that)