【问题标题】:React: How to make <td> collapse as column in a <tr> in mobile viewReact:如何使 <td> 在移动视图中折叠为 <tr> 中的列
【发布时间】:2021-10-22 02:12:43
【问题描述】:

我正在努力使我的网站在不同设备上看起来一致。

我有一张如下所示的表格:

我怎样才能使同一个表的行为,以便在移动设备上查看时,&lt;tr&gt; 中的&lt;td&gt; 将按列顺序排序,每个表数据旁边的&lt;th&gt; 如下所示:

我正在用 React 制作网站,所以如果有一种我不知道的在 React 中这样做的方法,那就更好了

【问题讨论】:

    标签: html css reactjs mobile css-tables


    【解决方案1】:

    能够通过媒体查询做到这一点:

    /* set for mobile breakpoint */
    @media (max-width: 1024px) {
        /* display th for desktop only, hide on mobile */
        .desktop {
            display: none;
        }
        
        /* arranges td as column in the tr */
        .mobile-flex {
            display: flex;
            width: 100%;
        }
    
        /* adds faux-headers on each td by reading "data-header" attribute of the td*/
        td:before {
        content: attr(data-header);
        display: block;
        font-weight: bold;
        margin-right: 10px;
        max-width: 110px;
        min-width: 110px;
        word-break: break-word;
        }
    }
    <table>
      <thead>
        <tr>
          <th class="desktop">Title</th>
          <th class="desktop">Author</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="mobile-flex" data-header="Title">Sample book title 1</td>
          <td class="mobile-flex" data-header="Author">Sample author name 1</td>
        </tr>
        <tr>
          <td class="mobile-flex" data-header="Title">Sample book title 2</td>
          <td class="mobile-flex" data-header="Author">Sample author name 2</td>
        </tr>
      </tbody>
    </table>

    【讨论】:

      【解决方案2】:

      媒体查询在这里可能无效,因为您要更改实际的 html。您可能希望使用 https://www.npmjs.com/package/react-breakpoints 之类的包来呈现不同的内容,具体取决于它是桌面设备还是移动设备。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-13
        • 2021-09-21
        • 2018-01-04
        • 2020-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多