我不想在描述为空时呈现标题
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>
什么是正确的方法而不是 !description 来检查它是否为空?
最佳答案
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。因为您可能会通过 Prop 发送数据。同样,如果您根本不想呈现此组件,那么这应该发生在父级中。
关于javascript - 检查 react 元素是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33219386/