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以获得更好的性能 - 固定时不会捕获键盘焦点
- 未固定时内容保持在文档流中