首页 > 解决方案 > 如何选择性地渲染反应表组件?

问题描述

在给定的代码片段中,如果标题等于 _id,我不想渲染组件,但以下条件渲染根本不会渲染(空表)。我应该使用什么条件语句?

return <table className='paleBlueRows' cellPadding= {11} cellSpacing={11}>
        <thead>
            <tr>{data[0] && columns.map((heading) => {
            if(heading!=='_id') <th>{heading}</th>
})}</tr> .....

标签: reactjsif-statement

解决方案


您可以Array.filter()在映射之前使用过滤掉标题,或者您可以返回nullfalse哪个React 将忽略。请注意,返回undefined(与不从函数返回任何内容相同)是无效的,并且会导致 React 发出警告。

所以,要么:

return (
  <table className="paleBlueRows" cellPadding={11} cellSpacing={11}>
    <thead>
      <tr>
        {data[0] &&
          columns
            .filter((heading) => heading !== "_id")
            .map((heading) => {
              return <th>{heading}</th>;
            })}
      </tr>
    </thead>
  </table>
);

或者:

return (
  <table className="paleBlueRows" cellPadding={11} cellSpacing={11}>
    <thead>
      <tr>
        {data[0] &&
          columns
            .filter((heading) => heading !== "_id")
            .map((heading) => {
              if (heading === "_id") return null;
              return <th>{heading}</th>;
            })}
      </tr>
    </thead>
  </table>
);

由于您正在渲染一个列表(使用.map()),请确保您设置了key从它返回的元素。我不知道是否columns可以包含重复值,或者关于其性质的任何其他内容,所以我无法提出准确的建议。如果不包含重复值,只需将其值设置为键,以便 React 知道在渲染之间发生更改columns时需要更新哪些元素。columns

return (
  <table className="paleBlueRows" cellPadding={11} cellSpacing={11}>
    <thead>
      <tr>
        {data[0] &&
          columns
            .filter((heading) => heading !== "_id")
            .map((heading) => {
              return <th key={heading}>{heading}</th>;
            })}
      </tr>
    </thead>
  </table>
);

推荐阅读