Back to Ant Design

Anchor

components/anchor/index.zh-CN.md

6.3.74.6 KB
Original Source

何时使用 {#when-to-use}

需要展现当前页面上可供跳转的锚点链接,以及快速在锚点之间跳转。

开发者注意事项:

4.24.0 起,由于组件从 class 重构成 FC,之前一些获取 ref 并调用内部实例方法的写法都会失效

代码演示 {#examples}

<!-- prettier-ignore -->

<code src="./demo/basic.tsx" iframe="200">基本</code> <code src="./demo/horizontal.tsx" iframe="200">横向 Anchor</code> <code src="./demo/static.tsx">静态位置</code> <code src="./demo/onClick.tsx">自定义 onClick 事件</code> <code src="./demo/customizeHighlight.tsx">自定义锚点高亮</code> <code src="./demo/targetOffset.tsx" iframe="200">设置锚点滚动偏移量</code> <code src="./demo/onChange.tsx">监听锚点链接改变</code> <code src="./demo/replace.tsx" iframe="200">替换历史中的 href</code> <code src="./demo/legacy-anchor.tsx" debug>废弃的 JSX 示例</code> <code src="./demo/style-class.tsx" iframe="200" version="6.0.0">自定义语义结构的样式和类</code> <code src="./demo/component-token.tsx" iframe="800" debug>组件 Token</code>

API

通用属性参考:通用属性

Anchor Props

参数说明类型默认值版本
affix固定模式boolean | Omit<AffixProps, 'offsetTop' | 'target' | 'children'>trueobject: 5.19.0
bounds锚点区域边界number5
classNames用于自定义组件内部各语义化结构的 class,支持对象或函数Record<SemanticDOM, string> | (info: { props })=> Record<SemanticDOM, string>-
getContainer指定滚动的容器() => HTMLElement() => window
getCurrentAnchor自定义高亮的锚点(activeLink: string) => string-
offsetTop距离窗口顶部达到指定偏移量后触发number
showInkInFixedaffix={false} 时是否显示小方块booleanfalse
styles用于自定义组件内部各语义化结构的行内 style,支持对象或函数Record<SemanticDOM, CSSProperties> | (info: { props })=> Record<SemanticDOM, CSSProperties>-
targetOffset锚点滚动偏移量,默认与 offsetTop 相同,例子number-
onChange监听锚点链接改变(currentActiveLink: string) => void-
onClickclick 事件的 handler(e: MouseEvent, link: object) => void-
items数据化配置选项内容,支持通过 children 嵌套{ key, href, title, target, children }[] 具体见-5.1.0
direction设置导航方向vertical | horizontalvertical5.2.0
replace替换浏览器历史记录中项目的 href 而不是推送它booleanfalse5.7.0

AnchorItem

参数说明类型默认值版本
key唯一标志string | number-
href锚点链接string-
target该属性指定在何处显示链接的资源string-
title文字内容ReactNode-
children嵌套的 Anchor Link,注意:水平方向该属性不支持AnchorItem[]-
replace替换浏览器历史记录中的项目 href 而不是推送它booleanfalse5.7.0

建议使用 items 形式。

参数说明类型默认值版本
href锚点链接string-
target该属性指定在何处显示链接的资源string-
title文字内容ReactNode-

Semantic DOM

<code src="./demo/_semantic.tsx" simplify="true"></code>

主题变量(Design Token){#design-token}

<ComponentTokenTable component="Anchor"></ComponentTokenTable>

FAQ

5.25.0+ 版本中,锚点跳转后,目标元素的 :target 伪类未按预期生效 {#faq-target-pseudo-class}

出于页面性能优化考虑,锚点跳转的实现方式从 window.location.href 调整为 window.history.pushState/replaceState。由于 pushState/replaceState 不会触发页面重载,因此浏览器不会自动更新 :target 伪类的匹配状态。可以手动构造完整URL:href = window.location.origin + window.location.pathname + '#xxx' 来解决这问题。

相关issues:#53143 #54255