2021SC@SDUSC
anchor锚点的位置用于快速定位链接的指定位置
先来看下接口内定义的参数
export interface AnchorProps {
// 前缀信息
prefixCls?: string;
// 类名
className?: string;
// 样式
style?: React.CSSProperties;
// 子类对象
children?: React.ReactNode;
// 距离窗口顶端的偏移量
offsetTop?: number;
// 区域边界
bounds?: number;
// 是否固定
affix?: boolean;
// 固定时是否显示小圆点
showInkInFixed?: boolean;
// 获取容器
getContainer?: () => AnchorContainer;
/** Return customize highlight anchor */
getCurrentAnchor?: () => string;
// 点击事件(跳转)
onClick?: (
e: React.MouseEvent<HTMLElement>,
link: { title: React.ReactNode; href: string },
) => void;
/** Scroll to target offset value, if none, it's offsetTop prop value or 0. */
// 锚点滚动偏移量,默认与offsetTop相同
targetOffset?: number;
/** Listening event when scrolling change active link */
// 用于监听锚点的变化
onChange?: (currentActiveLink: string) => void;
}
类定义
export default class Anchor extends React.Component<AnchorProps, AnchorState, ConfigConsumerProps> {
// 每个链接是由AnchorLink保存
static Link: typeof AnchorLink;
/// 默认固定不显示圆点
static defaultProps = {
affix: true,
showInkInFixed: false,
};
static contextType = ConfigContext;
state = {
activeLink: null,
};
content: ConfigConsumerProps;
private wrapperRef = React.createRef<HTMLDivElement>();
// 圆点样式
private inkNode: HTMLSpanElement;
// scroll scope's container
private scrollContainer: HTMLElement | Window;
// anchor的链接
private links: string[] = [];
// 鼠标滚轮的事件
private scrollEvent: any;
private animating: boolean;
private prefixCls?: string;
// 添加link
registerLink = (link: string) => {
if (!this.links.includes(link)) {
this.links.push(link);
}
};
// 删除link
unregisterLink = (link: string) => {
const index = this.links.indexOf(link);
if (index !== -1) {
this.links.splice(index, 1);
}
};
// 返回本容器或目标容器,都没有返回默认容器
getContainer = () => {
const { getTargetContainer } = this.context;
const { getContainer } = this.props;
const getFunc = getContainer || getTargetContainer || getDefaultContainer;
return getFunc();
};
componentDidMount() {
this.scrollContainer = this.getContainer();
this.scrollEvent = addEventListener(this.scrollContainer, 'scroll', this.handleScroll);
this.handleScroll();
}
componentDidUpdate() {
if (this.scrollEvent) {
const currentContainer = this.getContainer();
if (this.scrollContainer !== currentContainer) {
this.scrollContainer = currentContainer;
this.scrollEvent.remove();
this.scrollEvent = addEventListener(this.scrollContainer, 'scroll', this.handleScroll);
this.handleScroll();
}
}
this.updateInk();
}
componentWillUnmount() {
if (this.scrollEvent) {
this.scrollEvent.remove();
}
}
getCurrentAnchor(offsetTop = 0, bounds = 5): string {
const linkSections: Array<Section> = [];
const container = this.getContainer();
this.links.forEach(link => {
const sharpLinkMatch = sharpMatcherRegx.exec(link.toString());
if (!sharpLinkMatch) {
return;
}
const target = document.getElementById(sharpLinkMatch[1]);
if (target) {
const top = getOffsetTop(target, container);
if (top < offsetTop + bounds) {
linkSections.push({
link,
top,
});
}
}
});
if (linkSections.length) {
const maxSection = linkSections.reduce((prev, curr) => (curr.top > prev.top ? curr : prev));
return maxSection.link;
}
return '';
}
// 滚动到链接指定的位置
handleScrollTo = (link: string) => {
const { offsetTop, targetOffset } = this.props;
this.setCurrentActiveLink(link);
const container = this.getContainer();
const scrollTop = getScroll(container, true);
const sharpLinkMatch = sharpMatcherRegx.exec(link);
if (!sharpLinkMatch) {
return;
}
// 获取对应目标元素(link对应的)
const targetElement = document.getElementById(sharpLinkMatch[1]);
if (!targetElement) {
return;
}
// 计算对应元素所在位置
const eleOffsetTop = getOffsetTop(targetElement, container);
// 计算要移动到的位置
let y = scrollTop + eleOffsetTop;
// 查看是否匹配
y -= targetOffset !== undefined ? targetOffset : offsetTop || 0;
this.animating = true;
// 移动
scrollTo(y, {
callback: () => {
this.animating = false;
},
getContainer: this.getContainer,
});
};
saveInkNode = (node: HTMLSpanElement) => {
this.inkNode = node;
};
// 设置当前显示的链接位置
setCurrentActiveLink = (link: string) => {
const { activeLink } = this.state;
const { onChange, getCurrentAnchor } = this.props;
if (activeLink === link) {
return;
}
// https://github.com/ant-design/ant-design/issues/30584
this.setState({
activeLink: typeof getCurrentAnchor === 'function' ? getCurrentAnchor() : link,
});
onChange?.(link);
};
// 移动到指定位置
handleScroll = () => {
if (this.animating) {
return;
}
const { offsetTop, bounds, targetOffset } = this.props;
const currentActiveLink = this.getCurrentAnchor(
targetOffset !== undefined ? targetOffset : offsetTop || 0,
bounds,
);
this.setCurrentActiveLink(currentActiveLink);
};
// 保存当前存档点
updateInk = () => {
const { prefixCls, wrapperRef } = this;
const anchorNode = wrapperRef.current;
const linkNode = anchorNode?.getElementsByClassName(`${prefixCls}-link-title-active`)[0];
if (linkNode) {
this.inkNode.style.top = `${(linkNode as any).offsetTop + linkNode.clientHeight / 2 - 4.5}px`;
}
};
render = () => {
const { getPrefixCls, direction } = this.context;
// 保存组件需要用到的元素
const {
prefixCls: customizePrefixCls,
className = '',
style,
offsetTop,
affix,
showInkInFixed,
children,
} = this.props;
const { activeLink } = this.state;
const prefixCls = getPrefixCls('anchor', customizePrefixCls);
// To support old version react.
// Have to add prefixCls on the instance.
// https://github.com/facebook/react/issues/12397
this.prefixCls = prefixCls;
const inkClass = classNames(`${prefixCls}-ink-ball`, {
visible: activeLink,
});
const wrapperClass = classNames(
`${prefixCls}-wrapper`,
{
[`${prefixCls}-rtl`]: direction === 'rtl',
},
className,
);
const anchorClass = classNames(prefixCls, {
fixed: !affix && !showInkInFixed,
});
const wrapperStyle = {
maxHeight: offsetTop ? `calc(100vh - ${offsetTop}px)` : '100vh',
...style,
};
// 定义anchor保存到内容(属性信息)
const anchorContent = (
<div ref={this.wrapperRef} className={wrapperClass} style={wrapperStyle}>
<div className={anchorClass}>
<div className={`${prefixCls}-ink`}>
<span className={inkClass} ref={this.saveInkNode} />
</div>
{children}
</div>
</div>
);
// 返回组件
return (
<AnchorContext.Provider
value={{
registerLink: this.registerLink,
unregisterLink: this.unregisterLink,
activeLink: this.state.activeLink,
scrollTo: this.handleScrollTo,
onClick: this.props.onClick,
}}
>
{!affix ? (
anchorContent
) : (
<Affix offsetTop={offsetTop} target={this.getContainer}>
{anchorContent}
</Affix>
)}
</AnchorContext.Provider>
);
};
}