如何借助Ant Design的Anchor组件获取视口中组件的key值
实现实时显示视口中的Anchor锚点Key
核心方案
Ant Design的Anchor组件自带onChange事件,可直接监听当前激活的锚点key,无需手动绑定scroll事件。通过该事件回调更新状态,就能实时展示当前视口中的组件编号。
修改后的完整代码
import styled from "styled-components"; import { Anchor } from "antd"; import { useState } from "react"; export default function App() { const [currentView, setCurrentView] = useState("part-1"); // 初始化默认显示第一个组件 // 监听Anchor激活状态变化,更新当前视口组件key const handleAnchorChange = (activeKey) => { setCurrentView(activeKey); }; return ( <Wrap> <Anchor targetOffset={0} // 根据实际需要调整,比如sticky栏高度 style={{ display: "none" }} items={[ { key: "part-1", href: "#part-1", title: "Part 1" }, { key: "part-2", href: "#part-2", title: "Part 2" }, { key: "part-3", href: "#part-3", title: "Part 3" } ]} onChange={handleAnchorChange} // 绑定状态变化事件 /> <div className="fixed">currentcomponent : {currentView}</div> <div id="part-1" className="compo1"> components 1 </div> <div id="part-2" className="compo2"> components 2 </div> <div id="part-3" className="compo3"> components 3 </div> </Wrap> ); } const Wrap = styled.div` border: 3px solid black; width: 100vw; box-sizing: border-box; .fixed { position: sticky; top: 0; background: white; // 加背景避免被下方组件遮挡 padding: 10px; z-index: 1; } .compo1 { border: 3px solid red; display: flex; justify-content: center; align-items: center; width: 100vw; height: 70vh; } .compo2 { border: 3px solid blue; display: flex; justify-content: center; align-items: center; width: 100vw; height: 70vh; } .compo3 { border: 3px solid green; display: flex; justify-content: center; align-items: center; width: 100vw; height: 70vh; } `;
关键说明
onChange事件:Anchor的onChange会在滚动到对应锚点时触发,返回当前激活的锚点key,直接用这个值更新状态即可。- 初始化状态:给
currentView设置初始值part-1,避免页面加载时显示为空。 - 优化sticky栏:给顶部fixed栏加背景色和z-index,防止被下方组件遮挡,提升显示效果。
targetOffset调整:如果sticky栏有固定高度(比如50px),可将targetOffset设为对应数值,确保锚点定位更准确。
内容的提问来源于stack exchange,提问作者DgUZH
相关产品推荐
相关产品推荐

