ant-design/components/anchor/AnchorLink.tsx

81 lines
1.9 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';
import classNames from 'classnames';
import { AntAnchor } from './Anchor';
2016-10-28 14:02:55 +08:00
export interface AnchorLinkProps {
2016-11-03 16:45:13 +08:00
prefixCls?: string;
href: string;
title: React.ReactNode;
children?: any;
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 defaultProps = {
prefixCls: 'ant-anchor',
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);
}
2018-07-16 14:20:41 +08:00
componentWillReceiveProps(nextProps: AnchorLinkProps) {
const { href } = nextProps;
if (this.props.href !== href) {
this.context.antAnchor.unregisterLink(this.props.href);
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);
2016-11-09 14:40:31 +08:00
}
2016-11-03 16:45:13 +08:00
render() {
const {
prefixCls,
href,
title,
children,
} = this.props;
const active = this.context.antAnchor.activeLink === href;
const wrapperClassName = classNames(`${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 : ''}
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>
);
2016-11-03 16:45:13 +08:00
}
}