antd源码-anchor解析
整个anchor可以分为几部分:
- context的运用
- 滚动事件监听
- 组件didupdate的更新
context运用
anchor
static childContextTypes = {
antAnchor: PropTypes.object,
};
getChildContext() {
const antAnchor: AntAnchor = {
registerLink: (link: string) => {
if (!this.links.includes(link)) {
this.links.push(link);
}
},
unregisterLink: (link: string) => {
const index = this.links.indexOf(link);
if (index !== -1) {
this.links.splice(index, 1);
}
},
activeLink: this.state.activeLink,
scrollTo: this.handleScrollTo,
onClick: this.props.onClick,
};
return { antAnchor };
}
Link
static contextTypes = {
antAnchor: PropTypes.object,
};
父组件里面定义子组件的context属性,然后在子组件内部定义context,可以接受来自父组件的context属性,context是嵌套层次较深的兄弟组件之间通信的一种便捷方式
这样的使用方式是16.3之前的,16.3之后的使用又是另外一种。
在anchor组件中的link加载的时候,
调用父组件的注册Link方式。传递当前的href属性。点击的时候。调用scrollTo方法。
componentDidMount() {
this.context.antAnchor.registerLink(this.props.href);
}
componentDidUpdate({ href: prevHref }: AnchorLinkProps) {
const { href } = this.props;
if (prevHref !== href) {
this.context.antAnchor.unregisterLink(prevHref);
this.context.antAnchor.registerLink(href);
}
}
componentWillUnmount() {
this.context.antAnchor.unregisterLink(this.props.href);
}
handleClick = (e: React.MouseEvent<HTMLElement>) => {
const { scrollTo, onClick } = this.context.antAnchor;
const { href, title } = this.props;
if (onClick) {
onClick(e, { title, href });
}
scrollTo(href);
};
在anchor中,scrollTo绑定的是handleScrollTo方法,这个方法主要功能是
- 获得当前元素dom,计算需要滚动的top值,调用scrollTo方法,滚动到当前点击link匹配的页面容器块,
handleScrollTo = (link: string) => {
const { offsetTop, getContainer, targetOffset } = this.props as AnchorDefaultProps;
this.setCurrentActiveLink(link);
const container = getContainer();
const scrollTop = getScroll(container, true);
const sharpLinkMatch = sharpMatcherRegx.exec(link);
if (!sharpLinkMatch) {
return;
}
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,
});
};
getOffsetTop
这个函数比较重要。主要功能是计算元素滚动之后的top值。主要是靠
element.getBoundingClientRect(); 这个可以计算出当前top值,可以得到只读的left
, top
, right
, bottom
, x
, y
, width
, and height
当我们滚动乡下。元素超出页面的可是范围的时候。top就为负数了,top是随着页面的滚动而变化的。
function getOffsetTop(element: HTMLElement, container: AnchorContainer): number {
if (!element) {
return 0;
}
if (!element.getClientRects().length) {
return 0;
}
const rect = element.getBoundingClientRect();
if (rect.width || rect.height) {
if (container === window) {
container = element.ownerDocument!.documentElement!;
return rect.top - container.clientTop;
}
return rect.top - (container as HTMLElement).getBoundingClientRect().top;
}
return rect.top;
}
主动点击已经可以滚动了。
初始化
在anchor组件
- componentDidMount,添加滚动监听函数,调用handleScroll,并且初始化主动调用一次handleScroll是为了当我们刷新页面时滚动已经滚动了一段距离的处理。
- handleScroll,做了两件事,获得当前元素和设置滚动ink,也就是active的link是谁。
- 获得当前元素getCurrentAnchor ,这个是去获得每个和链接相关联的元素的offsetTop,如果获得的当前元素的top<我们主动传递的top值和bonds,说明这个元素的top已经消失在最上头了。就 将这个元素的top和href推送进数组,最后找到top最大的的元素返回。这个是页面刷新需要滚动的元素。就是当前active的元素。
- 设置active,此时,link已经高亮了。加入了active类名。会触发componentDidUpdate,调用updateInk,这个函数的作用是更新小圆点的位置到了link的位置。
componentDidMount() {
const { getContainer } = this.props as AnchorDefaultProps;
this.scrollContainer = getContainer();
this.scrollEvent = addEventListener(this.scrollContainer, 'scroll', this.handleScroll);
this.handleScroll();
}
componentDidUpdate() {
if (this.scrollEvent) {
const { getContainer } = this.props as AnchorDefaultProps;
const currentContainer = getContainer();
if (this.scrollContainer !== currentContainer) {
this.scrollContainer = currentContainer;
this.scrollEvent.remove();
this.scrollEvent = addEventListener(this.scrollContainer, 'scroll', this.handleScroll);
this.handleScroll();
}
}
this.updateInk();
}
getCurrentAnchor(offsetTop = 0, bounds = 5): string {
const { getCurrentAnchor } = this.props;
if (typeof getCurrentAnchor === 'function') {
return getCurrentAnchor();
}
const activeLink = '';
if (typeof document === 'undefined') {
return activeLink;
}
const linkSections: Array<Section> = [];
const { getContainer } = this.props as AnchorDefaultProps;
const container = 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 '';
}
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 = () => {
if (typeof document === 'undefined') {
return;
}
const { prefixCls } = this;
const anchorNode = ReactDOM.findDOMNode(this) as Element;
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`;
}
};
总结
- 多层组件之间的通信方式,context的运用。
- 利用状态的更新和组件的生命周期去做内容的渲染和更新。