Affix 固钉
滚动吸顶 / 吸底。用 IntersectionObserver 检测占位越界(无 scroll 节流开销,无 IO 环境自动回退 scroll 监听)。
基础用法
吸顶 / 吸底(向下滚动页面查看)
向下滚动页面,工具条触及虚线框顶部时吸顶,离开时复原。
吸顶状态:未固定
向下滚动页面,工具条触及虚线框顶部时吸顶,离开时复原。
吸底状态:未固定
import { useState } from 'react'
import { LhAffix, useLhLocale } from '@lh-ui/react'
export default function Demo() {
const { t } = useLhLocale()
const [topFixed, setTopFixed] = useState(false)
const [bottomFixed, setBottomFixed] = useState(false)
return (
<div className="demo-col">
<div className="demo-affix-zone">
<LhAffix offsetTop={8} onChange={setTopFixed}>
<div className="demo-affix-bar">{t('docs.affix.topBar')}</div>
</LhAffix>
<p className="demo-affix-text">{t('docs.affix.zoneHint')}</p>
</div>
<p>
{t('docs.affix.topState')}
{topFixed ? t('docs.affix.fixed') : t('docs.affix.unfixed')}
</p>
<div className="demo-affix-zone">
<LhAffix offsetBottom={8} onChange={setBottomFixed}>
<div className="demo-affix-bar">{t('docs.affix.bottomBar')}</div>
</LhAffix>
<p className="demo-affix-text">{t('docs.affix.zoneHint')}</p>
</div>
<p>
{t('docs.affix.bottomState')}
{bottomFixed ? t('docs.affix.fixed') : t('docs.affix.unfixed')}
</p>
</div>
)
}
offsetBottom 触发吸底(优先于 offsetTop);target 指定滚动监听容器(默认视口)。
Affix Props
| 属性 | 说明 | 类型 | 可选值 | 默认值 |
|---|---|---|---|---|
| offsetTop | 距视口顶部多少像素触发吸顶 | number | — | 0 |
| offsetBottom | 距视口底部多少像素触发吸底(优先于 offsetTop) | number | — | 0 |
| target | 滚动监听容器(选择器或元素,默认视口) | string | HTMLElement | — | — |
| children | 固钉内容(对应 plus 的默认插槽) | ReactNode | — | — |
| sx | 快速布局属性 | SxProps | — | — |
Affix 事件
| 事件 | 说明 | 回调签名 | Vue 对照 |
|---|---|---|---|
| onChange | 固定态切换时触发(进入或离开吸顶 / 吸底) | (fixed: boolean) => void | @change |
与 Vue 版的对应
offsetTop / offsetBottom / target / sx 与 lh-ui-plus 的 LhAffix 同名同义;
React 无插槽,plus 的默认插槽合并为 children,@change 对应 onChange。
防布局跳动
固定态以占位元素撑高(占位保持文档流高度),固定元素等宽于占位,内容不随滚动抖动。
无障碍
无特殊 role;固定态不影响文档流焦点顺序,固定元素层级走 --lh-affix-z-index(默认 900)。
样式
import '@lh-ui/react/style/affix'