mirror of
https://github.com/ant-design/ant-design.git
synced 2025-01-18 22:36:31 +08:00
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:
parent
7c06c1b96e
commit
e021147bb8
@ -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 = () => {
|
||||
|
@ -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>
|
||||
|
Loading…
Reference in New Issue
Block a user