Affix 固钉

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

何时使用

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

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

代码演示

基本

最简单的用法。

Affix固钉 - 图1

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

固定状态改变的回调

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

Affix固钉 - 图2

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import { Affix, Button } from 'choerodon-ui';
  4. ReactDOM.render(
  5. <Affix offsetTop={120} onChange={affixed => console.log(affixed)}>
  6. <Button>120px to affix top</Button>
  7. </Affix>,
  8. document.getElementById('container'),
  9. );

滚动容器

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

Affix固钉 - 图3

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

API

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

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

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