fix: Anchor not trigger getCurrentAnchor when scroll (#43916)

* docs: update doc

* fix: getCurrentLink not trigger when scroll
This commit is contained in:
二货爱吃白萝卜 2023-07-31 18:26:33 +08:00 committed by GitHub
parent 3f6defb22c
commit 4eb6074bb7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 27 additions and 7 deletions

View File

@ -216,6 +216,8 @@ const AnchorContent: React.FC<InternalAnchorProps> = (props) => {
};
const setCurrentActiveLink = useEvent((link: string) => {
// FIXME: Seems a bug since this compare is not equals
// `activeLinkRef` is parsed value which will always trigger `onChange` event.
if (activeLinkRef.current === link) {
return;
}
@ -234,14 +236,13 @@ const AnchorContent: React.FC<InternalAnchorProps> = (props) => {
if (animating.current) {
return;
}
if (typeof getCurrentAnchor === 'function') {
return;
}
const currentActiveLink = getInternalCurrentAnchor(
links,
targetOffset !== undefined ? targetOffset : offsetTop || 0,
bounds,
);
setCurrentActiveLink(currentActiveLink);
}, [dependencyListItem, targetOffset, offsetTop]);

View File

@ -560,9 +560,12 @@ describe('Anchor Render', () => {
{ legacyRoot: true },
);
expect(onChange).toHaveBeenCalledTimes(1);
fireEvent.click(container.querySelector(`a[href="#${hash2}"]`)!);
// Should be 2 times:
// 1. ''
// 2. hash1 (Since `getCurrentAnchor` still return same hash)
expect(onChange).toHaveBeenCalledTimes(2);
fireEvent.click(container.querySelector(`a[href="#${hash2}"]`)!);
expect(onChange).toHaveBeenCalledTimes(3);
expect(onChange).toHaveBeenLastCalledWith(`#${hash2}`);
});
@ -614,6 +617,22 @@ describe('Anchor Render', () => {
fireEvent.scroll(window || document);
}).not.toThrow();
});
it('should repeat trigger when scrolling', () => {
const getCurrentAnchor = jest.fn();
render(
<Anchor
getCurrentAnchor={getCurrentAnchor}
items={[{ key: 'test', href: null as unknown as string, title: 'test' }]}
/>,
);
for (let i = 0; i < 100; i += 1) {
getCurrentAnchor.mockReset();
fireEvent.scroll(window || document);
expect(getCurrentAnchor).toHaveBeenCalled();
}
});
});
describe('horizontal anchor', () => {

View File

@ -31,7 +31,7 @@ For displaying anchor hyperlinks on page and jumping between them.
<code src="./demo/onChange.tsx">Listening for anchor link change</code>
<code src="./demo/replace.tsx" iframe="200">Replace href in history</code>
<code src="./demo/legacy-anchor.tsx" debug>Deprecated JSX demo</code>
<code src="./demo/component-token.tsx" debug>Component Token</code>
<code src="./demo/component-token.tsx" iframe="800" debug>Component Token</code>
## API

View File

@ -32,7 +32,7 @@ group:
<code src="./demo/onChange.tsx">监听锚点链接改变</code>
<code src="./demo/replace.tsx" iframe="200">替换历史中的 href</code>
<code src="./demo/legacy-anchor.tsx" debug>废弃的 JSX 示例</code>
<code src="./demo/component-token.tsx" debug>组件 Token</code>
<code src="./demo/component-token.tsx" iframe="800" debug>组件 Token</code>
## API