[英]Check if react element is empty
當描述為空時我不想呈現標題
var description = <MyElement />; // render will return nothing in render in some cases
if (!description) { // this will not work because its an object (reactelement)
return null;
}
<div>
{title}
{description}
</div>
什么是正確的方式而不是!描述檢查它是否為空?
var description, title;
if (this.props.description) {
description = <Description description={this.props.description} />;
if (this.props.title) {
title = <Title title={this.props.title} />;
}
}
<div>
{title}
{description}
</div>
要么:
render() {
const { description, title } = this.props;
return (
<div>
{title && description && <Title title={title} />}
{description && <Description description={description} />}
</div>
);
}
Imo更好的做法是,如果不需要你的描述元素,那么它不會被渲染,而不是在它的渲染中返回null。 因為您可能會通過道具發送數據。 同樣,如果您根本不想渲染此組件,那么這應該發生在父組件中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.