检查 React 元素是否为空

16

当描述为空时,我不想呈现标题

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?


你有任何状态/属性可以检查以查看描述是否应为空吗?最好使用这些进行检查,而不是检查元素的子元素。 - J3Y
不是真的,数据是由一些属性构建的,这些属性在myelement组件中被转换/过滤。如果没有办法,我需要将这个逻辑移动到父组件中。然后我可以在这些属性中进行检查。 - Alexander Schranz
1个回答

3
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>
  );
}

在IT技术方面,我认为更好的做法是如果你的描述元素不需要,则不要渲染它,而不是在其渲染中返回null。因为你可能会通过一个prop发送数据。同样,如果你不想渲染这个组件,那么应该在父级中实现。


1
所以唯一的解决方案就是将数据转换/过滤的逻辑移动到父元素中,并在该变量上进行检查吗? - Alexander Schranz
1
是的,据我所知,这是React自上而下渲染方案的有意部分。 - machineghost

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接