Affix固钉

将页面元素钉在可视范围。

何时使用

当内容区域比较长,需要滚动页面时,这部分内容对应的操作或者导航需要在滚动范围内始终展现。常用于侧边菜单和按钮组合。

页面可视范围过小时,慎用此功能以免遮挡页面内容。

代码演示

Affix固钉 - 图1

基本

最简单的用法。

TypeScript

JavaScript

Affix固钉 - 图2

  1. import React, { useState } from 'react';
  2. import { Affix, Button } from 'antd';
  3. const Demo: React.FC = () => {
  4. const [top, setTop] = useState(10);
  5. const [bottom, setBottom] = useState(10);
  6. return (
  7. <>
  8. <Affix offsetTop={top}>
  9. <Button type="primary" onClick={() => setTop(top + 10)}>
  10. Affix top
  11. </Button>
  12. </Affix>
  13. <br />
  14. <Affix offsetBottom={bottom}>
  15. <Button type="primary" onClick={() => setBottom(bottom + 10)}>
  16. Affix bottom
  17. </Button>
  18. </Affix>
  19. </>
  20. );
  21. };
  22. ReactDOM.render(<Demo />, mountNode);

Affix固钉 - 图3

滚动容器

target 设置 Affix 需要监听其滚动事件的元素,默认为 window

TypeScript

JavaScript

Affix固钉 - 图4

  1. import React, { useState } from 'react';
  2. import { Affix, Button } from 'antd';
  3. const Demo: React.FC = () => {
  4. const [container, setContainer] = useState<HTMLDivElement | null>(null);
  5. return (
  6. <div className="scrollable-container" ref={setContainer}>
  7. <div className="background">
  8. <Affix target={() => container}>
  9. <Button type="primary">Fixed at the top of container</Button>
  10. </Affix>
  11. </div>
  12. </div>
  13. );
  14. };
  15. ReactDOM.render(<Demo />, mountNode);

Affix固钉 - 图5

固定状态改变的回调

可以获得是否固定的状态。

TypeScript

JavaScript

Affix固钉 - 图6

  1. import { Affix, Button } from 'antd';
  2. ReactDOM.render(
  3. <Affix offsetTop={120} onChange={affixed => console.log(affixed)}>
  4. <Button>120px to affix top</Button>
  5. </Affix>,
  6. mountNode,
  7. );

API

成员说明类型默认值
offsetBottom距离窗口底部达到指定偏移量后触发number-
offsetTop距离窗口顶部达到指定偏移量后触发number-
target设置 Affix 需要监听其滚动事件的元素,值为一个返回对应 DOM 元素的函数() => HTMLElement() => window
onChange固定状态改变时触发的回调函数function(affixed)-

注意:Affix 内的元素不要使用绝对定位,如需要绝对定位的效果,可以直接设置 Affix 为绝对定位:

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

FAQ

Affix 使用 target 绑定容器时,元素会跑到容器外。

从性能角度考虑,我们只监听容器滚动事件。如果希望任意滚动,你可以在窗体添加滚动监听:https://codesandbox.io/s/2xyj5zr85p

相关 issue:#3938 #5642 #16120