antdesign 使用锚点组件和哈希路由冲突

在react项目开发中,有场景需要使用锚点组件,但是react项目使用的又是哈希路由, 锚点组件的item 会被渲染成a标签,通过herf属性, 和被定位元素的id来做锚点定位,所以就导致了,点击item会改变地址栏的url, 所以在使用锚点时通过onClick 事件的事件对象 MouseEvent.preventDefault(); 来阻止默认事件,

const Anchor1: React.FC = () => {
    const handlerClick = (MouseEvent: any) => {
        MouseEvent.preventDefault();
    };
    return (
        <Row>
            <Col span={16}>
                <div id="part-1" style={{ height: "100vh", background: "rgba(255,0,0,0.02)", fontSize: "30px" }}>
                    第一个锚点
                </div>
                <div id="part-2" style={{ height: "100vh", background: "rgba(0,255,0,0.02)", fontSize: "30px" }}>
                    第二个锚点
                </div>
                <div id="part-3" style={{ height: "100vh", background: "rgba(0,0,255,0.02)", fontSize: "30px" }}>
                    第三个锚点
                </div>
            </Col>
            <Col span={8}>
                <Anchor
                    getContainer={() => document.getElementById("content") as AnchorContainer}
                    onClick={handlerClick}
                    items={[
                        {
                            key: "part-1",
                            href: "#part-1",
                            title: "Part 1",
                            target: "part-1"
                        },
                        {
                            key: "part-2",
                            href: "#part-2",
                            title: "Part 2",
                            target: "part-2"
                        },
                        {
                            key: "part-3",
                            href: "#part-3",
                            title: "Part 3",
                            target: "part-3"
                        }
                    ]}
                />
            </Col>
        </Row>
    );
};

getContainer={() => document.getElementById(“content”) as AnchorContainer} 方法返回一个元素 来指定滚动的容器

<Layout className={style.content}>
   <Content id="content" style={{ padding: "0", backgroundColor: "#fff" }}>
      <Anchor1 />
   Content>
Layout>

你可能感兴趣的:(报错,javascript,前端,react.js,antd,antdsign,锚点)