reactjs - Conditonal Rendering of components
问题描述
I find myself writing code like this quite frequently, to avoid deeply nested statements to determine return values e.g.:
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>
}
I'm not 100% satisfied with that solution, (repetetive code, return statement gets somewhat bloated and it's quite hard to look at the return statement to see whats happening) and i'm anxious that it's considered bad style. Is there a more readable / cleaner way to do this?
解决方案
使用逻辑 AND ( &&
) 的更短/更简单的条件渲染。
React 忽略输出中的布尔值。只有 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>
);
}
推荐阅读
- php - 打开页面时删除url中的某些部分
- javascript - 当用户单击/移出文本框时删除错误验证消息
- ios - 它们是否相当于原生 iOS 模拟器开发的反应原生“热重载”?
- html - 寻找正确的 Laravel 路线 | 从数据库中获取照片
- c - 我的快速排序实现不起作用
- google-colaboratory - Google Colab 中的运行时和会话有什么区别?
- r - 在数据框的不同行之间的管道内计算
- python - 如何限制 Jupyter Notebook 允许使用的 RAM 量?
- macos - aws cli 自动缩放命令不返回到 shell promot
- django - Django将runserver日志打印到文件