mirror of
https://github.com/ant-design/ant-design.git
synced 2024-12-24 07:28:28 +08:00
dd37457048
* update: 添加AntAnchor类型 * update: 完成代码逻辑 * update: 添加测试 * update: 点击锚点不记录历史 * update: 添加示例 * docs: 更新文档 * update: 更改onClick事件里的link为对象 * update: 优化代码 * update: 修改propClick为onClick
81 lines
1.9 KiB
TypeScript
81 lines
1.9 KiB
TypeScript
import * as React from 'react';
|
|
import * as PropTypes from 'prop-types';
|
|
import classNames from 'classnames';
|
|
import { AntAnchor } from './Anchor';
|
|
|
|
export interface AnchorLinkProps {
|
|
prefixCls?: string;
|
|
href: string;
|
|
title: React.ReactNode;
|
|
children?: any;
|
|
}
|
|
|
|
export default class AnchorLink extends React.Component<AnchorLinkProps, any> {
|
|
static defaultProps = {
|
|
prefixCls: 'ant-anchor',
|
|
href: '#',
|
|
};
|
|
|
|
static contextTypes = {
|
|
antAnchor: PropTypes.object,
|
|
};
|
|
|
|
context: {
|
|
antAnchor: AntAnchor;
|
|
};
|
|
|
|
componentDidMount() {
|
|
this.context.antAnchor.registerLink(this.props.href);
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
handleClick = (e: React.MouseEvent<HTMLElement>) => {
|
|
const { scrollTo, onClick } = this.context.antAnchor;
|
|
const { href, title } = this.props;
|
|
if (onClick) {
|
|
onClick(e, { title, href });
|
|
}
|
|
scrollTo(href);
|
|
}
|
|
|
|
render() {
|
|
const {
|
|
prefixCls,
|
|
href,
|
|
title,
|
|
children,
|
|
} = this.props;
|
|
const active = this.context.antAnchor.activeLink === href;
|
|
const wrapperClassName = classNames(`${prefixCls}-link`, {
|
|
[`${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 : ''}
|
|
onClick={this.handleClick}
|
|
>
|
|
{title}
|
|
</a>
|
|
{children}
|
|
</div>
|
|
);
|
|
}
|
|
}
|