在React开发中,我们经常会用到html的条件渲染,如使用三目运算来判断展示哪个html
let a = true
return (
<div>
{
a ? <div>111</div> : ''
}
</div>
)
利用&& 或者 || 运算符的短路写法可以实现更简的代码。
const queryCriteria = () => {
let a = true;
let b = false;
return (
<div>
{
a && <div>a为true时展示</div>
}
{
b || <div>b为false时展示</div>
}
</div>
)
}
页面展示:
原理:
如:a == c && f
当a==c为true时,才会执行f
注:
&&运算符只有两边同为true时,结果才为true,所以左边为true时,便会继续执行右边。
若左边为false时结果注定为false,便不会继续执行右边。
如:a == c || f
当a==c为false时,才会执行f
注:
||运算符只要其中一个为true,结果就为true,所以左边为false时,仍会执行右边来判断是否为true.
若左边为true,则结果注定为true,便不会继续执行右边。