웹 프론트엔드 프런트엔드 Q&A 반응에서 테이블 헤더 고정을 달성하는 방법

반응에서 테이블 헤더 고정을 달성하는 방법

Jan 09, 2023 am 10:25 AM
react

React에서 고정 테이블 헤더를 구현하는 방법: 1. Ant Design의 Table 구성 요소를 통해 고정 테이블 헤더를 구현합니다. 2. "rc-table"을 사용하여 모바일 단말기에서 고정 테이블 헤더를 구현합니다. div의 onscroll 이벤트 div의 scrollLeft 속성입니다.

반응에서 테이블 헤더 고정을 달성하는 방법

이 튜토리얼의 운영 환경: Windows 10 시스템, 반응 버전 18.0.0, Dell G3 컴퓨터.

반응 헤더를 수정하는 방법은 무엇입니까?

React 테이블 고정 헤더/잠금 열

Ant Design의 Table 컴포넌트는 고정 헤더 및 잠긴 열 기능을 가지고 있지만 Ant Design Mobile에는 Table 컴포넌트가 없습니다. 모바일 단말기에서 고정된 테이블 헤더와 잠긴 열의 기능을 구현하려면 rc-table을 사용할 수 있어야 하며, 물론 직접 작성할 수도 있습니다.

AntD의 테이블을 분석하면 고정 헤더가 있는 테이블이 각각 div에 중첩된 두 개의

태그로 구성되어 있음을 알 수 있습니다. ;. 아래는 만 포함된 테이블 내용입니다. 아래 div의 onscroll 이벤트를 수신하고 위 div의 scrollLeft 속성을 변경하여 테이블이 가로로 스크롤될 때 테이블 헤더도 동시에 스크롤되도록 해야 합니다. 고정 열은 th 및 td의 CSS 속성 위치를 고정으로 설정하고 왼쪽 또는 오른쪽을 0으로 설정하여 달성됩니다. 동시에 잠긴 열이 항상 상단에 표시되도록 z-index를 설정합니다.

원리를 이해하고 나면 코드 작성이 더 쉬워집니다.

components/ScrollableTable/interface.tsx

import * as React from 'react';
export declare type AlignType = 'left' | 'center' | 'right';
export interface ColumnType {
  align?: AlignType;
  className?: string;
  dataKey?: string;
  fixed?: boolean;
  title?: React.ReactNode;
  width?: number;
  render?: (value: any, record: any, index: number) => React.ReactNode;
}
export interface TableProps {
  className?: string;
  style?: React.CSSProperties;
  columns?: ColumnType[];
  dataSource?: any[];
  width?: number;
  height?: number;
}

components/ScrollableTable/index.tsx

import React, { FunctionComponent, useRef } from 'react';
import { TableProps, ColumnType } from './interface';
import './index.less';
const ScrollableTable: FunctionComponent<any> = (props: TableProps) => {
  const style: React.CSSProperties = props.style || {};
  const maxHeight: string = props.width ? (props.height + &#39;px&#39;) : &#39;unset&#39;;
  const columns: ColumnType[] = props.columns || [];
  const dataSource: any[] = props.dataSource || [];
  let maxWidth: number = 0;
  if (props.width) style.width = props.width;
  if (columns.length === 0) {
    columns.push({
      dataKey: &#39;key&#39;
    });
  }
  columns.forEach((column: ColumnType) => {
    const width: number = column.width || 50;
    maxWidth += width;
  });
  const fixedColumns: number[][] = getFixedColumns(columns);
  const leftFixedColumns: number[] = fixedColumns[0];
  const rightFixedColumns: number[] = fixedColumns[1];
  const tableBody: any = useRef();
  const handleScroll = (target: any) => {
    const scrollLeft: number = target.scrollLeft;
    const tableHeaders: any = target.parentElement.getElementsByClassName(&#39;st-table-header&#39;);
    if (tableHeaders.length > 0) {
      tableHeaders[0].scrollLeft = scrollLeft;
    }
  };
  return (
    <div
      className={classNames(&#39;st-table-container&#39;, props.className)}
      style={style}
    >
      <div className="st-table-header">
        <table>
          <colgroup>
            {
              renderCols(columns)
            }
          </colgroup>
          <thead className="st-table-thead">
            <tr>
              {
                columns.map((column: ColumnType, index: number) => {
                  const align: any = column.align || undefined;
                  const title: React.ReactNode = column.title || &#39;&#39;;
                  const fixed: string = leftFixedColumns.includes(index) ? &#39;left&#39; : (rightFixedColumns.includes(index) ? &#39;right&#39; : &#39;&#39;);
                  const fixedClassName: string = fixed ? (&#39;st-table-cell-fix-&#39; + fixed) : &#39;&#39;;
                  return (
                    <th
                      key={index}
                      className={classNames(&#39;st-table-cell&#39;, fixedClassName, column.className)}
                      style={{textAlign: align}}
                    >
                      {title}
                    </th>
                  );
                })
              }
            </tr>
          </thead>
        </table>
      </div>
      <div
        ref={tableBody}
        className="st-table-body"
        style={{maxHeight: maxHeight}}
        onScroll={(e: any) => handleScroll(e.currentTarget)}
      >
        <table style={{width: maxWidth, minWidth: &#39;100%&#39;}}>
          <colgroup>
              {
                renderCols(columns)
              }
            </colgroup>
            <tbody className="st-table-tbody">
              {
                dataSource.map((record: any, index: number) => (
                  <tr key={index} className="st-table-row">
                    {
                      renderCells(columns, leftFixedColumns, rightFixedColumns, record, index)
                    }
                  </tr>
                ))
              }
            </tbody>
        </table>
      </div>
    </div>
  );
};
function classNames(...names: (string | undefined)[]) {
  const currentNames: string[] = [];
  names.forEach((name: (string | undefined)) => {
    if (name) currentNames.push(name);
  });
  return currentNames.join(&#39; &#39;);
}
function getFixedColumns(columns: ColumnType[]) {
  const total: number = columns.length;
  const leftFixedColumns: number[] = [];
  const rightFixedColumns: number[] = [];
  if (columns[0].fixed) {
    for (let i = 0; i < total; i++) {
      if (columns[i].fixed) {
        leftFixedColumns.push(i);
      } else {
        break;
      }
    }
  }
  if (columns[total - 1].fixed) {
    for (let i = total - 1; i >= 0; i--) {
      if (columns[i].fixed) {
        if (!leftFixedColumns.includes(i)) rightFixedColumns.push(i);
      } else {
        break;
      }
    }
  }
  return [leftFixedColumns, rightFixedColumns];
}
function renderCols(columns: ColumnType[]) {
  return columns.map((column: ColumnType, index: number) => {
    const width: number = column.width || 50;
    return (
      <col
        key={index}
        style={{width: width, minWidth: width}}
      />
    );
  });
}
function renderCells(columns: ColumnType[], leftFixedColumns: number[], rightFixedColumns: number[], record: any, index: number) {
  return columns.map((column: ColumnType, index: number) => {
    const align: any = column.align || undefined;
    const fixed: string = leftFixedColumns.includes(index) ? &#39;left&#39; : (rightFixedColumns.includes(index) ? &#39;right&#39; : &#39;&#39;);
    const className: string = classNames(&#39;st-table-cell&#39;, column.className, fixed ? (&#39;st-table-cell-fix-&#39; + fixed) : &#39;&#39;);
    const rawValue: any = (column.dataKey && column.dataKey in record) ? record[column.dataKey] : undefined;
    let value: any = undefined;
    if (column.render) {
      value = column.render(rawValue, record, index);
    } else {
      value = (rawValue === undefined || rawValue === null) ? &#39;&#39; : String(rawValue);
    }
    return (
      <td
        key={index}
        className={className}
        style={{textAlign: align}}
      >
        {value}
      </td>
    );
  });
}
export default ScrollableTable;

components/ScrollableTable/index.less

.st-table-container {
  border: 1px solid #f0f0f0;
  border-right: 0;
  border-bottom: 0;
  font-size: 14px;
  .st-table-header {
    border-right: 1px solid #f0f0f0;
    overflow: hidden;
    table {
      border-collapse: separate;
      border-spacing: 0;
      table-layout: fixed;
      width: 100%;
      thead.st-table-thead {
        tr {
          th.st-table-cell {
            background: #fafafa;
            border-bottom: 1px solid #f0f0f0;
            border-right: 1px solid #f0f0f0;
            color: rgba(0, 0, 0, .85);
            font-weight: 500;
            padding: 8px;
            text-align: left;
            &:last-child {
              border-right: 0;
            }
          }
        }
      }
    }
  }
  .st-table-body {
    overflow: auto scroll;
    border-bottom: 1px solid #f0f0f0;
    border-right: 1px solid #f0f0f0;
    table {
      border-collapse: separate;
      border-spacing: 0;
      table-layout: fixed;
      tbody.st-table-tbody {
        tr.st-table-row {
          td.st-table-cell  {
            border-bottom: 1px solid #f0f0f0;
            border-right: 1px solid #f0f0f0;
            color: rgba(0, 0, 0, .65);
            padding: 8px;
            text-align: left;
            &:last-child {
              border-right: 0;
            }
          }
          &:last-child {
            td.st-table-cell  {
              border-bottom: 0;
            }
          }
        }
      }
    }
  }
  table {
    .st-table-cell {
      &.st-table-cell-fix-left {
        background: #fff;
        position: sticky;
        left: 0;
        z-index: 2;
      }
      &.st-table-cell-fix-right {
        background: #fff;
        position: sticky;
        right: 0;
        z-index: 2;
      }
    }
  }
}
로그인 후 복사

그런 다음 다음과 같이 사용할 수 있습니다.

views/Test/index.tsx
import React, { FunctionComponent } from &#39;react&#39;;
import Page from &#39;../../components/Page&#39;;
import ScrollableTable from &#39;../../components/ScrollableTable&#39;;
import StoreProvider from &#39;../../stores/products/context&#39;;
import &#39;./index.less&#39;;
const Test: FunctionComponent<any> = (props: any) => {
  let records: any[] = [{
    id: 1,
    productName: &#39;淡泰&#39;,
    amount1: 198,
    amount2: 200,
    amount3: 205.5,
    currency: &#39;人民币&#39;,
    ca: &#39;Amy&#39;
  }, {
    productName: &#39;方润&#39;,
    amount1: 105.5,
    amount2: 100,
    amount3: 108,
    currency: &#39;港元&#39;,
    ca: &#39;Baby&#39;
  }, {
    productName: &#39;医疗基金-1&#39;,
    amount1: 153,
    amount2: 150,
    amount3: 155,
    currency: &#39;人民币&#39;,
    ca: &#39;Emily&#39;
  }, {
    productName: &#39;医疗基金-2&#39;,
    amount1: 302,
    amount2: 300,
    amount3: 290,
    currency: &#39;美元&#39;,
    ca: &#39;Baby&#39;
  }, {
    productName: &#39;医疗基金-3&#39;,
    amount1: 108.8,
    amount2: 100,
    amount3: 130,
    currency: &#39;人民币&#39;,
    ca: &#39;Amy&#39;
  }, {
    productName: &#39;医疗基金-4&#39;,
    amount1: 205,
    amount2: 200,
    amount3: 208,
    currency: &#39;美元&#39;,
    ca: &#39;吴丹&#39;
  }, {
    productName: &#39;医疗基金-5&#39;,
    amount1: 315.5,
    amount2: 300,
    amount3: 280,
    currency: &#39;人民币&#39;,
    ca: &#39;Baby&#39;
  }, {
    productName: &#39;医疗基金-6&#39;,
    amount1: 109,
    amount2: 95,
    amount3: 106,
    currency: &#39;人民币&#39;,
    ca: &#39;Emily&#39;
  }, {
    productName: &#39;恒大私募债&#39;,
    amount1: 213,
    amount2: 200,
    amount3: 208,
    currency: &#39;港元&#39;,
    ca: &#39;吴丹&#39;
  }];
  const totalRecord: any = {
    productName: &#39;合计&#39;,
    amount1: {},
    amount2: {},
    amount3: {}
  };
  records.forEach((record: any) => {
    const currency: string = record.currency;
    [&#39;amount1&#39;, &#39;amount2&#39;, &#39;amount3&#39;].forEach((key: string) => {
      const value: any = totalRecord[key];
      if (!(currency in value)) value[currency] = 0;
      value[currency] += record[key];
    });
  });
  records.push(totalRecord);
  const columns: any[] = [{
    dataKey: &#39;productName&#39;,
    title: &#39;产品名称&#39;,
    width: 90,
    fixed: true
  }, {
    dataKey: &#39;amount1&#39;,
    title: <React.Fragment>上周缴款金额<br/>(万)</React.Fragment>,
    width: 140,
    align: &#39;center&#39;,
    className: &#39;amount&#39;,
    render: calculateTotal
  }, {
    dataKey: &#39;amount2&#39;,
    title: <React.Fragment>上周预约金额<br/>(万)</React.Fragment>,
    width: 140,
    align: &#39;center&#39;,
    className: &#39;amount&#39;,
    render: calculateTotal
  }, {
    dataKey: &#39;amount3&#39;,
    title: <React.Fragment>待本周跟进金额<br/>(万)</React.Fragment>,
    width: 140,
    align: &#39;center&#39;,
    className: &#39;amount&#39;,
    render: calculateTotal
  }, {
    dataKey: &#39;currency&#39;,
    title: &#39;币种&#39;,
    width: 80
  }, {
    dataKey: &#39;ca&#39;,
    title: &#39;CA&#39;,
    width: 80
  }];
  return (
    <StoreProvider>
      <Page
        {...props}
        title="销售统计"
        className="test"
      >
        <div style={{padding: 15}}>
          <ScrollableTable
            width={window.innerWidth - 30}
            height={196}
            columns={columns}
            dataSource={records}
          />
        </div>
      </Page>
    </StoreProvider>
  );
};
function calculateTotal(value: any) {
  if (value instanceof Object) {
    const keys: any[] = Object.keys(value);
    return (
      <React.Fragment>
        {
          keys.map((key: string, index: number) => (
            <span key={index}>
              {`${value[key].toFixed(2)}万${key}`}
            </span>
          ))
        }
      </React.Fragment>
    )
  }
  return value.toFixed(2);
}
export default Test;

views/Test/index.less

.st-table-container {
  .st-table-body {
    td.st-table-cell.amount {
      padding-right: 20px !important;
      text-align: right !important;
      span {
        display: block;
      }
    }
  }
}
로그인 후 복사

추천 학습: "react 비디오 튜토리얼"

위 내용은 반응에서 테이블 헤더 고정을 달성하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

React와 WebSocket을 사용하여 실시간 채팅 앱을 구축하는 방법 React와 WebSocket을 사용하여 실시간 채팅 앱을 구축하는 방법 Sep 26, 2023 pm 07:46 PM

React와 WebSocket을 사용하여 실시간 채팅 애플리케이션을 구축하는 방법 소개: 인터넷의 급속한 발전과 함께 실시간 커뮤니케이션이 점점 더 주목을 받고 있습니다. 실시간 채팅 앱은 현대 사회 생활과 직장 생활에서 필수적인 부분이 되었습니다. 이 글에서는 React와 WebSocket을 사용하여 간단한 실시간 채팅 애플리케이션을 구축하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. 1. 기술적 준비 실시간 채팅 애플리케이션 구축을 시작하기 전에 다음과 같은 기술과 도구를 준비해야 합니다. React: 구축을 위한 것

React 프론트엔드와 백엔드 분리 가이드: 프론트엔드와 백엔드의 분리 및 독립적 배포를 달성하는 방법 React 프론트엔드와 백엔드 분리 가이드: 프론트엔드와 백엔드의 분리 및 독립적 배포를 달성하는 방법 Sep 28, 2023 am 10:48 AM

React 프론트엔드와 백엔드 분리 가이드: 프론트엔드와 백엔드 분리 및 독립적 배포를 달성하는 방법, 구체적인 코드 예제가 필요합니다. 오늘날의 웹 개발 환경에서는 프론트엔드와 백엔드 분리가 추세가 되었습니다. . 프런트엔드 코드와 백엔드 코드를 분리함으로써 개발 작업을 보다 유연하고 효율적으로 수행하고 팀 협업을 촉진할 수 있습니다. 이 기사에서는 React를 사용하여 프런트엔드와 백엔드 분리를 달성하고 이를 통해 디커플링 및 독립적 배포 목표를 달성하는 방법을 소개합니다. 먼저 프론트엔드와 백엔드 분리가 무엇인지 이해해야 합니다. 전통적인 웹 개발 모델에서는 프런트엔드와 백엔드가 결합되어 있습니다.

React와 Flask를 사용하여 간단하고 사용하기 쉬운 웹 애플리케이션을 구축하는 방법 React와 Flask를 사용하여 간단하고 사용하기 쉬운 웹 애플리케이션을 구축하는 방법 Sep 27, 2023 am 11:09 AM

React와 Flask를 사용하여 간단하고 사용하기 쉬운 웹 애플리케이션을 구축하는 방법 소개: 인터넷의 발전과 함께 웹 애플리케이션의 요구 사항은 점점 더 다양해지고 복잡해지고 있습니다. 사용 편의성과 성능에 대한 사용자 요구 사항을 충족하기 위해 최신 기술 스택을 사용하여 네트워크 애플리케이션을 구축하는 것이 점점 더 중요해지고 있습니다. React와 Flask는 프런트엔드 및 백엔드 개발을 위한 매우 인기 있는 프레임워크이며, 함께 잘 작동하여 간단하고 사용하기 쉬운 웹 애플리케이션을 구축합니다. 이 글에서는 React와 Flask를 활용하는 방법을 자세히 설명합니다.

React 반응형 디자인 가이드: 적응형 프런트엔드 레이아웃 효과를 얻는 방법 React 반응형 디자인 가이드: 적응형 프런트엔드 레이아웃 효과를 얻는 방법 Sep 26, 2023 am 11:34 AM

React 반응형 디자인 가이드: 적응형 프런트엔드 레이아웃 효과를 달성하는 방법 모바일 장치의 인기와 멀티스크린 경험에 대한 사용자 요구가 증가함에 따라 반응형 디자인은 현대 프런트엔드 개발에서 중요한 고려 사항 중 하나가 되었습니다. 현재 가장 인기 있는 프런트 엔드 프레임워크 중 하나인 React는 개발자가 적응형 레이아웃 효과를 달성하는 데 도움이 되는 풍부한 도구와 구성 요소를 제공합니다. 이 글에서는 React를 사용하여 반응형 디자인을 구현하는 데 대한 몇 가지 지침과 팁을 공유하고 참조할 수 있는 구체적인 코드 예제를 제공합니다. React를 사용한 Fle

React와 RabbitMQ를 사용하여 안정적인 메시징 앱을 구축하는 방법 React와 RabbitMQ를 사용하여 안정적인 메시징 앱을 구축하는 방법 Sep 28, 2023 pm 08:24 PM

React 및 RabbitMQ를 사용하여 안정적인 메시징 애플리케이션을 구축하는 방법 소개: 최신 애플리케이션은 실시간 업데이트 및 데이터 동기화와 같은 기능을 달성하기 위해 안정적인 메시징을 지원해야 합니다. React는 사용자 인터페이스 구축을 위한 인기 있는 JavaScript 라이브러리인 반면 RabbitMQ는 안정적인 메시징 미들웨어입니다. 이 기사에서는 React와 RabbitMQ를 결합하여 안정적인 메시징 애플리케이션을 구축하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. RabbitMQ 개요:

React 코드 디버깅 가이드: 프런트엔드 버그를 빠르게 찾아 해결하는 방법 React 코드 디버깅 가이드: 프런트엔드 버그를 빠르게 찾아 해결하는 방법 Sep 26, 2023 pm 02:25 PM

React 코드 디버깅 가이드: 프런트엔드 버그를 빠르게 찾고 해결하는 방법 소개: React 애플리케이션을 개발할 때 애플리케이션을 충돌시키거나 잘못된 동작을 유발할 수 있는 다양한 버그에 자주 직면하게 됩니다. 따라서 디버깅 기술을 익히는 것은 모든 React 개발자에게 필수적인 능력입니다. 이 기사에서는 프런트엔드 버그를 찾고 해결하기 위한 몇 가지 실용적인 기술을 소개하고 독자가 React 애플리케이션에서 버그를 빠르게 찾고 해결하는 데 도움이 되는 특정 코드 예제를 제공합니다. 1. 디버깅 도구 선택: In Re

React Router 사용자 가이드: 프런트엔드 라우팅 제어 구현 방법 React Router 사용자 가이드: 프런트엔드 라우팅 제어 구현 방법 Sep 29, 2023 pm 05:45 PM

ReactRouter 사용자 가이드: 프런트엔드 라우팅 제어 구현 방법 단일 페이지 애플리케이션의 인기로 인해 프런트엔드 라우팅은 무시할 수 없는 중요한 부분이 되었습니다. React 생태계에서 가장 널리 사용되는 라우팅 라이브러리인 ReactRouter는 풍부한 기능과 사용하기 쉬운 API를 제공하여 프런트 엔드 라우팅 구현을 매우 간단하고 유연하게 만듭니다. 이 기사에서는 ReactRouter를 사용하는 방법을 소개하고 몇 가지 구체적인 코드 예제를 제공합니다. ReactRouter를 먼저 설치하려면 다음이 필요합니다.

React와 Google BigQuery를 사용하여 빠른 데이터 분석 애플리케이션을 구축하는 방법 React와 Google BigQuery를 사용하여 빠른 데이터 분석 애플리케이션을 구축하는 방법 Sep 26, 2023 pm 06:12 PM

React와 Google BigQuery를 사용하여 빠른 데이터 분석 애플리케이션을 구축하는 방법 소개: 오늘날 정보 폭발 시대에 데이터 분석은 다양한 산업에서 없어서는 안 될 연결 고리가 되었습니다. 그중에서도 빠르고 효율적인 데이터 분석 애플리케이션을 구축하는 것은 많은 기업과 개인이 추구하는 목표가 되었습니다. 이 기사에서는 React와 Google BigQuery를 사용하여 빠른 데이터 분석 애플리케이션을 구축하는 방법을 소개하고 자세한 코드 예제를 제공합니다. 1. 개요 React는 빌드를 위한 도구입니다.

See all articles