条件渲染时可以使用if/else,但当更复杂或需要判断的变量更多时,推荐分离组件替代
//if
function render() {
return condition && <span>Rendered when `truthy`</span>
}
// unless
function render() {
return condition || <span>Rendered when `falsey`</span>
}
// if- else (tidy one - liners)
function render() {
return condition
? <span>Rendered when `truthy`</span>
: <span>Rendered when `falsey`</span>
}
// if- else (big blocks)
function render() {
return condition ? (
<span>
Rendered when `truthy`
</span>
) : (
<span>
Rendered when `falsey`
</span>
)
}
使用falsy或truthy(非布尔值)合并逻辑运算符
const Oops = ({showFirst,dontShowSecond}) => (
<div>
{showFirst && 'first'}
{dontShowSecond || 'second'}
</div>
)
使用!!将输入转换成布尔值
const Oops = ({showFirst,dontShowSecond}) => (
<div>
{!!showFirst && 'first'}
{!!dontShowSecond || 'second'}
</div>
)