跳转到内容

Affix 固钉

滚动时让元素固定在视口中。适用于导航、工具栏或操作按钮。

import { Affix } from 'asterui'

基本用法

滚动超过元素位置后变为固定定位。

import { Affix, Button } from 'asterui'

function App() {
  return (
      <Affix offsetTop={80}>
        <Button color="primary">Affixed Button</Button>
      </Affix>
    )
}

export default App

回调函数

固定状态改变时收到通知。

import { Affix, Button } from 'asterui'
import { useState } from 'react'

function App() {
  const [affixed, setAffixed] = useState(false)
  
  return (
      <Affix offsetTop={80} onChange={setAffixed}>
        <Button type={affixed ? 'primary' : 'neutral'}>
          {affixed ? 'Affixed!' : 'Not Affixed'}
        </Button>
      </Affix>
    )
}

export default App

固定到底部

将元素固定到视口底部。

import { Affix, Button } from 'asterui'

function App() {
  return (
      <Affix offsetBottom={20}>
        <Button color="secondary">Bottom Affixed</Button>
      </Affix>
    )
}

export default App

自定义容器

在可滚动容器内固定。

Sticky Header
import { Affix } from 'asterui'

function App() {
  return (
      <div id="scroll-container" className="h-64 overflow-auto">
        <Affix offsetTop={0} target={() => document.getElementById('scroll-container')!}>
          <div className="bg-primary text-primary-content p-2">
            Sticky Header
          </div>
        </Affix>
        {/* Scrollable content */}
      </div>
    )
}

export default App
属性描述类型默认值
children要固定的内容React.ReactNode-
offsetTop固定时距离顶部的偏移量(像素)number-
offsetBottom固定时距离底部的偏移量(像素)number-
target滚动目标元素() => HTMLElement | Window-
onChange固定状态改变时的回调函数(affixed: boolean) => void-
className额外的 CSS 类名string-
  • 使用 CSS position: sticky 以获得更好的性能
  • 固定时不会捕获键盘焦点
  • 未固定时内容保持在文档流中