Affix

Affix (고정 컨테이너)

Affix는 길이가 긴 웹 페이지에서 컴포넌트를 뷰포트에 고정시킬 때 사용해요. 메뉴나 액션 버튼 같은 곳에 흔히 쓰이죠.

출처: 문서

본문

언제 사용하나요

길이가 긴 웹 페이지에서 컴포넌트를 뷰포트에 고정시키는 데 유용해요. 메뉴와 액션에서 흔히 쓰이죠.

Affix는 페이지의 다른 콘텐츠를 덮어서는 안 된다는 점에 주의하세요. 특히 뷰포트 크기가 작을 때요.

개발자 참고

5.10.0 버전 이후부터 Affix를 FC(Function Component)로 다시 작성했어요. ref를 얻거나 내부 인스턴스 메서드를 호출하는 일부 방법은 더 이상 동작하지 않아요.

예제 (Examples)

기본 (Basic)

가장 단순한 사용법이에요.

import React from 'react';
import { Affix, Button } from 'antd';

const App: React.FC = () => {
  const [top, setTop] = React.useState<number>(100);
  const [bottom, setBottom] = React.useState<number>(100);
  return (
    <>
      <Affix offsetTop={top}>
        <Button type="primary" onClick={() => setTop(top + 10)}>
          Affix top
        </Button>
      </Affix>
      <br />
      <Affix offsetBottom={bottom}>
        <Button type="primary" onClick={() => setBottom(bottom + 10)}>
          Affix bottom
        </Button>
      </Affix>
    </>
  );
};

export default App;

Callback

고정(affixed) 상태를 가진 콜백을 사용해요.

import React from 'react';
import { Affix, Button } from 'antd';

const App: React.FC = () => (
  <Affix offsetTop={120} onChange={(affixed) => console.log(affixed)}>
    <Button>120px to affix top</Button>
  </Affix>
);

export default App;

스크롤 컨테이너.

Affix에 target을 설정하면 그 target 요소의 스크롤 이벤트를 감지해요(기본값은 window).

import React from 'react';
import { Affix, Button } from 'antd';

const containerStyle: React.CSSProperties = {
  width: '100%',
  height: 100,
  overflow: 'auto',
  boxShadow: '0 0 0 1px #1677ff',
  scrollbarWidth: 'thin',
  scrollbarGutter: 'stable',
};

const style: React.CSSProperties = {
  width: '100%',
  height: 1000,
};

const App: React.FC = () => {
  const [container, setContainer] = React.useState<HTMLDivElement | null>(null);
  return (
    <div style={containerStyle} ref={setContainer}>
      <div style={style}>
        <Affix target={() => container}>
          <Button type="primary">Fixed at the top of container</Button>
        </Affix>
      </div>
    </div>
  );
};

export default App;

API

공통 props 참고: Common props

속성 설명 타입 기본값 버전 전역 설정
offsetBottom 뷰포트 하단으로부터의 오프셋(픽셀) number - ×
offsetTop 뷰포트 상단으로부터의 오프셋(픽셀) number 0 ×
target 스크롤 가능한 영역 DOM 노드를 지정 () => Window | HTMLElement | null () => window ×
onChange Affix 상태가 바뀔 때의 콜백 (affixed?: boolean) => void - ×

참고: Affix의 자식은 position: absolute 속성을 가질 수 없어요. 하지만 Affix 자신에는 position: absolute를 설정할 수 있어요.

<Affix style={{ position: 'absolute', top: y, left: x }}>...</Affix>

FAQ

Affix에서 target으로 컨테이너에 바인딩할 때, 요소가 컨테이너 밖으로 이동하는 경우가 있어요. {#faq-target-container}

성능상의 이유로 컨테이너의 스크롤 이벤트만 듣고 있어요. 그래도 원한다면 커스텀 리스너를 추가할 수 있어요: https://codesandbox.io/s/stupefied-maxwell-ophqnm?file=/index.js

관련 이슈: #3938 #5642 #16120

Affix를 가로 스크롤 컨테이너에서 사용하면 요소의 left 위치가 올바르지 않아요. {#faq-horizontal-scroll}

Affix는 일반적으로 단방향 스크롤 영역에만 적용 가능하고, 세로 스크롤 컨테이너에서만 사용을 지원해요. 가로 컨테이너에서 사용하려면 네이티브 position: sticky 속성으로 구현하는 것을 고려해 볼 수 있어요.

관련 이슈: #29108

더 알아보기 (Learn more)