ant-design/components/anchor/AnchorLink.tsx

89 lines
2.3 KiB
TypeScript
Raw Normal View History

import * as React from 'react';
2018-08-07 21:07:52 +08:00
import * as PropTypes from 'prop-types';
2019-02-02 18:30:40 +08:00
import { polyfill } from 'react-lifecycles-compat';
import classNames from 'classnames';
import { AntAnchor } from './Anchor';
import { ConfigConsumer, ConfigConsumerProps } from '../config-provider';
2016-10-28 14:02:55 +08:00
export interface AnchorLinkProps {
2016-11-03 16:45:13 +08:00
prefixCls?: string;
href: string;
target?: string;
title: React.ReactNode;
children?: React.ReactNode;
className?: string;
2016-10-28 14:02:55 +08:00
}
2019-02-02 18:30:40 +08:00
class AnchorLink extends React.Component<AnchorLinkProps, any> {
2016-11-03 16:45:13 +08:00
static defaultProps = {
href: '#',
2016-11-03 16:45:13 +08:00
};
static contextTypes = {
antAnchor: PropTypes.object,
2016-11-03 16:45:13 +08:00
};
context: {
antAnchor: AntAnchor;
};
componentDidMount() {
this.context.antAnchor.registerLink(this.props.href);
}
2019-02-02 18:30:40 +08:00
componentDidUpdate({ href: prevHref }: AnchorLinkProps) {
const { href } = this.props;
if (prevHref !== href) {
this.context.antAnchor.unregisterLink(prevHref);
2018-07-16 14:20:41 +08:00
this.context.antAnchor.registerLink(href);
}
}
componentWillUnmount() {
this.context.antAnchor.unregisterLink(this.props.href);
2016-11-03 16:45:13 +08:00
}
2016-11-09 14:22:38 +08:00
handleClick = (e: React.MouseEvent<HTMLElement>) => {
const { scrollTo, onClick } = this.context.antAnchor;
const { href, title } = this.props;
if (onClick) {
onClick(e, { title, href });
}
scrollTo(href);
2018-12-07 20:02:01 +08:00
};
2016-11-09 14:40:31 +08:00
renderAnchorLink = ({ getPrefixCls }: ConfigConsumerProps) => {
const { prefixCls: customizePrefixCls, href, title, children, className, target } = this.props;
const prefixCls = getPrefixCls('anchor', customizePrefixCls);
const active = this.context.antAnchor.activeLink === href;
const wrapperClassName = classNames(className, `${prefixCls}-link`, {
2016-11-03 16:45:13 +08:00
[`${prefixCls}-link-active`]: active,
});
const titleClassName = classNames(`${prefixCls}-link-title`, {
[`${prefixCls}-link-title-active`]: active,
});
2016-11-09 14:22:38 +08:00
return (
<div className={wrapperClassName}>
2016-11-09 14:40:31 +08:00
<a
className={titleClassName}
2016-11-09 14:40:31 +08:00
href={href}
title={typeof title === 'string' ? title : ''}
target={target}
onClick={this.handleClick}
2016-11-09 14:22:38 +08:00
>
2016-11-09 14:40:31 +08:00
{title}
</a>
{children}
2016-11-09 14:22:38 +08:00
</div>
);
2018-12-07 20:02:01 +08:00
};
render() {
2018-12-07 20:02:01 +08:00
return <ConfigConsumer>{this.renderAnchorLink}</ConfigConsumer>;
}
2016-11-03 16:45:13 +08:00
}
2019-02-02 18:30:40 +08:00
polyfill(AnchorLink);
export default AnchorLink;