ant-design/components/anchor/AnchorLink.tsx

79 lines
2.1 KiB
TypeScript
Raw Normal View History

import classNames from 'classnames';
2022-06-22 14:57:09 +08:00
import * as React from 'react';
import { ConfigContext } from '../config-provider';
import warning from '../_util/warning';
2022-06-22 14:57:09 +08:00
import type { AntAnchor } from './Anchor';
import AnchorContext from './context';
2016-10-28 14:02:55 +08:00
export interface AnchorLinkBaseProps {
2016-11-03 16:45:13 +08:00
prefixCls?: string;
href: string;
target?: string;
title: React.ReactNode;
className?: string;
2016-10-28 14:02:55 +08:00
}
export interface AnchorLinkProps extends AnchorLinkBaseProps {
children?: React.ReactNode;
}
const AnchorLink: React.FC<AnchorLinkProps> = (props) => {
const { href = '#', title, prefixCls: customizePrefixCls, children, className, target } = props;
const context = React.useContext<AntAnchor | undefined>(AnchorContext);
const { registerLink, unregisterLink, scrollTo, onClick, activeLink, direction } = context || {};
2018-07-16 14:20:41 +08:00
React.useEffect(() => {
registerLink?.(href);
return () => {
unregisterLink?.(href);
};
}, [href]);
2016-11-09 14:22:38 +08:00
2022-12-06 18:18:38 +08:00
const handleClick = (e: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => {
onClick?.(e, { title, href });
scrollTo?.(href);
2018-12-07 20:02:01 +08:00
};
2016-11-09 14:40:31 +08:00
// =================== Warning =====================
if (process.env.NODE_ENV !== 'production') {
warning(
!children || direction !== 'horizontal',
'Anchor.Link',
'`Anchor.Link children` is not supported when `Anchor` direction is horizontal',
);
}
const { getPrefixCls } = React.useContext(ConfigContext);
const prefixCls = getPrefixCls('anchor', customizePrefixCls);
const active = activeLink === href;
const wrapperClassName = classNames(`${prefixCls}-link`, className, {
[`${prefixCls}-link-active`]: active,
});
const titleClassName = classNames(`${prefixCls}-link-title`, {
[`${prefixCls}-link-title-active`]: active,
});
return (
<div className={wrapperClassName}>
<a
className={titleClassName}
href={href}
title={typeof title === 'string' ? title : ''}
target={target}
onClick={handleClick}
>
{title}
</a>
{direction !== 'horizontal' ? children : null}
</div>
);
};
2019-02-02 18:30:40 +08:00
export default AnchorLink;