Affix固钉

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

何时使用

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

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

代码演示

Affix固钉 - 图1

基本

最简单的用法。

  1. import { Affix, Button } from 'antd';
  2. class Demo extends React.Component {
  3. state = {
  4. top: 10,
  5. bottom: 10,
  6. };
  7. render() {
  8. return (
  9. <div>
  10. <Affix offsetTop={this.state.top}>
  11. <Button
  12. type="primary"
  13. onClick={() => {
  14. this.setState({
  15. top: this.state.top + 10,
  16. });
  17. }}
  18. >
  19. Affix top
  20. </Button>
  21. </Affix>
  22. <br />
  23. <Affix offsetBottom={this.state.bottom}>
  24. <Button
  25. type="primary"
  26. onClick={() => {
  27. this.setState({
  28. bottom: this.state.bottom + 10,
  29. });
  30. }}
  31. >
  32. Affix bottom
  33. </Button>
  34. </Affix>
  35. </div>
  36. );
  37. }
  38. }
  39. ReactDOM.render(<Demo />, mountNode);

Affix固钉 - 图2

滚动容器

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

  1. import { Affix, Button } from 'antd';
  2. class Demo extends React.Component {
  3. render() {
  4. return (
  5. <div
  6. className="scrollable-container"
  7. ref={node => {
  8. this.container = node;
  9. }}
  10. >
  11. <div className="background">
  12. <Affix target={() => this.container}>
  13. <Button type="primary">Fixed at the top of container</Button>
  14. </Affix>
  15. </div>
  16. </div>
  17. );
  18. }
  19. }
  20. ReactDOM.render(<Demo />, mountNode);

Affix固钉 - 图3

固定状态改变的回调

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

  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