ant-design/components/anchor/AnchorLink.tsx

92 lines
2.2 KiB
TypeScript
Raw Normal View History

2016-10-28 14:02:55 +08:00
import React from 'react';
import classNames from 'classnames';
2016-11-03 16:45:13 +08:00
import AnchorHelper, { scrollTo } from './anchorHelper';
2016-10-28 14:02:55 +08:00
export interface AnchorLinkProps {
href: string;
2016-11-03 16:45:13 +08:00
onClick: (href: string) => void;
active?: boolean;
prefixCls?: string;
children?: any;
title?: Element;
bounds: number;
target?: () => HTMLElement | Window;
2016-10-28 14:02:55 +08:00
}
2016-11-03 16:45:13 +08:00
export default class AnchorLink extends React.Component<AnchorLinkProps, any> {
static contextTypes = {
anchorHelper: React.PropTypes.any,
};
2016-10-28 16:53:59 +08:00
2016-11-03 16:45:13 +08:00
static childContextTypes = {
anchorHelper: React.PropTypes.any,
};
static defaultProps = {
href: '#',
prefixCls: 'ant-anchor',
};
context: {
anchorHelper: AnchorHelper;
};
constructor(props, context) {
super(props, context);
}
getChildContext() {
return {
anchorHelper: this.context.anchorHelper,
};
}
2016-11-09 14:22:38 +08:00
2016-11-03 16:45:13 +08:00
renderAnchorLink = (child) => {
const { href } = child.props;
if (href) {
this.context.anchorHelper.addLink(href);
return React.cloneElement(child, {
onClick: this.context.anchorHelper.scrollTo,
prefixCls: this.props.prefixCls,
});
}
return child;
}
2016-11-09 14:22:38 +08:00
scrollTo = (e) => {
2016-11-09 14:40:31 +08:00
const { onClick, href } = this.props;
const { anchorHelper } = this.context;
e.preventDefault();
2016-11-09 14:40:31 +08:00
if (onClick) {
onClick(href);
} else {
e.stopPreventDefault();
const scrollToFn = anchorHelper ? anchorHelper.scrollTo : scrollTo;
scrollToFn(href);
}
}
2016-11-03 16:45:13 +08:00
render() {
2016-11-09 14:40:31 +08:00
const { prefixCls, href, children, title, bounds } = this.props;
2016-11-03 16:45:13 +08:00
const { anchorHelper } = this.context;
const active = anchorHelper && anchorHelper.getCurrentAnchor(bounds) === href;
const cls = classNames({
2016-11-03 16:45:13 +08:00
[`${prefixCls}-link`]: true,
[`${prefixCls}-link-active`]: active,
});
2016-11-09 14:22:38 +08:00
return (
<div className={cls}>
2016-11-09 14:40:31 +08:00
<a
2016-11-09 14:22:38 +08:00
ref={(component) => component && active && anchorHelper ? anchorHelper.setActiveAnchor(component) : null}
className={`${prefixCls}-link-title`}
2016-11-09 14:40:31 +08:00
onClick={this.scrollTo}
href={href}
2016-11-09 14:22:38 +08:00
>
2016-11-09 14:40:31 +08:00
{title}
</a>
2016-11-09 14:22:38 +08:00
{React.Children.map(children, this.renderAnchorLink)}
</div>
);
2016-11-03 16:45:13 +08:00
}
}