javascript - 检查 react 元素是否为空

标签 javascript reactjs

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

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/

相关文章:

javascript - 为什么我的占位符不会出现在 TextInput 中

javascript - 使用计时器清理 Socket.io session 数据

javascript - 递归循环包装?

html - antd选择元素: how can I disable typing?

javascript - 使用 react refs 来关注兄弟元素

javascript - Javascript 中不明确的函数声明

javascript - Microsoft Edge 和 window.resizeTo

javascript - React Form onChange 不更新状态

javascript - 为什么我可以在 React 中省略带括号的 return 语句

javascript - React hooks map 不是一个函数