Affix 固钉

如果项目中使用的是 1.x 版本的基础组件(@alifd/next),请在左侧导航顶部切换组件版本。

安装方法

  1. 在命令行中执行以下命令npm install @icedesign/base@latest -S

Guide

何时使用

当用户需要将某个组件固定在页面的某个位置时,可以使用 Affix 组件进行固定。

API

固钉

参数说明类型默认值
prefix品牌样式前缀String'next-'
container设置 Affix 需要监听滚动事件的容器元素签名:Function() => ReactElement返回值:{ReactElement} 目标容器元素的实例Function() => window
offsetTop距离窗口顶部达到指定偏移量后触发Number-
offsetBottom距离窗口底部达到制定偏移量后触发Number-
onAffix当元素的样式发生固钉样式变化时触发的回调函数签名:Function(affixed: Boolean) => void参数:affixed: {Boolean} 元素是否被固钉Function() => {}
className自定义样式类名String-

代码示例

基本

也就意味着当页面往下滚动时,当 Affix 元素接触到浏览器边框时,此时会将 Affix 钉住。最简单的用法。默认情况下,Affix 的默认目标容器元素是整个 window,并且 offsetTop = 0

Affix 固钉 - 图1

查看源码在线预览

  1. import { Affix, Button } from "@icedesign/base";
  2. ReactDOM.render(
  3. <div className="custom-affix-wrapper">
  4. <Affix>
  5. <Button type="secondary">Affixed Button</Button>
  6. </Affix>
  7. </div>,
  8. mountNode
  9. );
  1. .custom-affix-wrapper {
  2. padding: 40px 0;
  3. }

自定义目标容器

可以通过 container 属性设置 Affix 组件需要监听其滚动事件的元素,该属性接收一个函数作为参数,默认为 () => window

Affix 固钉 - 图2

查看源码在线预览

  1. import { Affix, Button } from "@icedesign/base";
  2. class Demo extends React.Component {
  3. _containerRefHandler(ref) {
  4. this.container = ref;
  5. }
  6. render() {
  7. return (
  8. <div
  9. className="custom-affix-container"
  10. ref={this._containerRefHandler.bind(this)}
  11. >
  12. <div className="a-wrapper">
  13. <Affix
  14. container={() => this.container}
  15. offsetTop={0}
  16. onAffix={affixed => console.log(affixed)}
  17. >
  18. <Button type="secondary">Affixed Button</Button>
  19. </Affix>
  20. </div>
  21. </div>
  22. );
  23. }
  24. }
  25. ReactDOM.render(<Demo />, mountNode);
  1. .custom-affix-container {
  2. height: 150px;
  3. overflow-y: scroll;
  4. background: url(https://img.alicdn.com/tfs/TB1AbJXSpXXXXXJXpXXXXXXXXXX-32-32.jpg) repeat 50% 50%;
  5. }
  6. .custom-affix-container .a-wrapper {
  7. padding-top: 50px;
  8. height: 500px;
  9. }

自定义偏移量

可以通过 offsetTopoffsetBottom 自定义偏移量。

Affix 固钉 - 图3

查看源码在线预览

  1. import { Affix, Button } from "@icedesign/base";
  2. ReactDOM.render(
  3. <div className="custom-affix-wrapper">
  4. <Affix offsetBottom={0}>
  5. <Button type="secondary">Affixed Button</Button>
  6. </Affix>
  7. </div>,
  8. mountNode
  9. );
  1. .custom-affix-wrapper {
  2. padding: 40px 0;
  3. }

相关区块

Affix 固钉 - 图4

暂无相关区块