antdesign uses anchor component and hash routing conflict

In react project development, there are scenarios that require the use of anchor components, but the react project uses hash routing. The item of the anchor component will be rendered into an a tag, anchored through the herf attribute and the id of the positioned element. Click positioning, so as a result, clicking the item will change the URL of the address bar, so when using the anchor point, use the event object MouseEvent.preventDefault(); of the onClick event to prevent the default event.

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>
    );
};

The getContainer={() => document.getElementById(“content”) as AnchorContainer} method returns an element to specify the scrolling container

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

Guess you like

Origin blog.csdn.net/weixin_42560424/article/details/133066673