ant-design/components/anchor/AnchorLink.tsx

82 lines
2.1 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';
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;
title: React.ReactNode;
children?: any;
className?: string;
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 = {
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);
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 } = 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 : ''}
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
}