【发布时间】:2020-10-05 23:26:44
【问题描述】:
我发现自己经常编写这样的代码,以避免使用深度嵌套的语句来确定返回值,例如:
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 语句来了解发生了什么),我很担心它被认为是不好的风格。有没有更易读/更简洁的方法来做到这一点?
【问题讨论】:
标签: reactjs coding-style