问题描述
我发现自己经常编写这样的代码,以避免深度嵌套的语句来确定返回值,例如:
function Warning(props){
return <h1> Warning! </h1>
}
function SomeComponent(props){
const [showAtTop,setShowAtTop] = useState(false);
//...
const ShowWarningAtTop = showAtTop
? <Warning></Warning>
: null
const ShowAtBottom = showAtTop
? null
: <Warning></Warning>
return <div>
{showWarningAtTop}
<div> Main Content</div>
{showWarningAtBottom}
</div>
}
我对这种解决方案不是100%满意的(重复的代码,return语句有点肿,很难通过return语句查看正在发生的事情),并且我担心它被认为是不好的风格。有更可读/更清洁的方法吗?
解决方法
使用逻辑AND(&&
)进行更简短的条件渲染。
Inline If with Logical && Operator
React忽略输出中的布尔值。仅对组件需要进行反应以返回null
,以指示它们什么都不渲染,组件内 中的任何内容都可以返回true / false,并且react将忽略并且不渲染文字值。
您还可以在JSX中自动关闭空标签。
function SomeComponent(props){
const [showAtTop,setShowAtTop] = useState(false);
//...
return (
<div>
{showAtTop && <Warning />}
<div> Main Content</div>
{showAtTop && <Warning />}
</div>
);
}