ant-design/components/anchor/AnchorLink.tsx

85 lines
2.2 KiB
TypeScript
Raw Normal View History

import * as React from 'react';
import classNames from 'classnames';
import type { AntAnchor } from './Anchor';
import type { ConfigConsumerProps } from '../config-provider';
import { ConfigConsumer } from '../config-provider';
import AnchorContext from './context';
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
}
class AnchorLink extends React.Component<AnchorLinkProps, any, AntAnchor> {
2016-11-03 16:45:13 +08:00
static defaultProps = {
href: '#',
2016-11-03 16:45:13 +08:00
};
static contextType = AnchorContext;
2016-11-03 16:45:13 +08:00
context: AntAnchor;
componentDidMount() {
this.context.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.unregisterLink(prevHref);
this.context.registerLink(href);
2018-07-16 14:20:41 +08:00
}
}
componentWillUnmount() {
this.context.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;
const { href, title } = this.props;
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.activeLink === href;
const wrapperClassName = classNames(
`${prefixCls}-link`,
{
[`${prefixCls}-link-active`]: active,
},
className,
);
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
export default AnchorLink;