fix: Anchor should trigger onChange when have getCurrentAnchor (#30601)

* fix: Anchor should trigger onChange when have getCurrentAnchor

close #30584

* test: add test case
This commit is contained in:
afc163 2021-05-20 21:36:53 +08:00 committed by GitHub
parent 7c06c1b96e
commit e021147bb8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 13 deletions

View File

@ -163,12 +163,6 @@ export default class Anchor extends React.Component<AnchorProps, AnchorState, Co
}
getCurrentAnchor(offsetTop = 0, bounds = 5): string {
const { getCurrentAnchor } = this.props;
if (typeof getCurrentAnchor === 'function') {
return getCurrentAnchor();
}
const linkSections: Array<Section> = [];
const container = this.getContainer();
this.links.forEach(link => {
@ -229,14 +223,15 @@ export default class Anchor extends React.Component<AnchorProps, AnchorState, Co
setCurrentActiveLink = (link: string) => {
const { activeLink } = this.state;
const { onChange } = this.props;
if (activeLink !== link) {
this.setState({
activeLink: link,
});
onChange?.(link);
const { onChange, getCurrentAnchor } = this.props;
if (activeLink === link) {
return;
}
// https://github.com/ant-design/ant-design/issues/30584
this.setState({
activeLink: typeof getCurrentAnchor === 'function' ? getCurrentAnchor() : link,
});
onChange?.(link);
};
handleScroll = () => {

View File

@ -359,6 +359,23 @@ describe('Anchor Render', () => {
expect(onChange).toHaveBeenCalledWith(hash2);
});
// https://github.com/ant-design/ant-design/issues/30584
it('should trigger onChange when have getCurrentAnchor', async () => {
const hash1 = getHashUrl();
const hash2 = getHashUrl();
const onChange = jest.fn();
const wrapper = mount<Anchor>(
<Anchor onChange={onChange} getCurrentAnchor={() => hash1}>
<Link href={`#${hash1}`} title={hash1} />
<Link href={`#${hash2}`} title={hash2} />
</Anchor>,
);
expect(onChange).toHaveBeenCalledTimes(1);
wrapper.instance().handleScrollTo(hash2);
expect(onChange).toHaveBeenCalledTimes(2);
expect(onChange).toHaveBeenCalledWith(hash2);
});
it('invalid hash', async () => {
const wrapper = mount<Anchor>(
<Anchor>