react组件-菜单按钮滚动到对应的锚点位置

920 阅读1分钟

首先 npm install smoothscroll-polyfill --save 先安装依赖,这个依赖是 smoothscroll.js 页面平滑滚动插件 然后写组件,下面是代码

import React from "react";
import smoothscroll from "smoothscroll-polyfill";

type Props = {
    href: string[]; // 放id,需要到的地方,按照顺序展示
    content: any[]; // 放内容,可以是文案和代码
    boxClassName?: string | undefined; // 外面div的className
};

class Anchor extends React.Component<Props> {
    componentDidMount(): void {
        smoothscroll.polyfill();
    }

    scrollToAnchor = (anchorName: string): void => {
        if (anchorName) {
            const anchorElement = document.getElementById(anchorName);
            if (anchorElement) {
                anchorElement.scrollIntoView({ block: "start", behavior: "smooth" });
            }
        }
    };



    render(): JSX.Element {
        const { href, content, boxClassName } = this.props;
        return (
            <div className={boxClassName}>
                {href && href.length > 0
                    ? href.map((item: string, index: number) => {
                        return (
                            <a onClick={() => this.scrollToAnchor(item)} key={item}>
                                {content[index]}
                            </a>
                        );
                })
                : null}
            </div>
        );
    }
}

export default Anchor;

// 引用组件

import Anchor from '../components/public/anchor' //引用对应的位置

<Anchor
    href={["top", "center", "foor"]}
    content={[
        <span className="btn1">按钮</span>,
        <span>按钮</span>,
        <span>按钮</span>,
    ]}
 />
// 上面的span需要设置className,去控制样式 
// 然后 把要跳转的位置加上id,比如下面有三个位置锚点
<div className={style.bg_1} id="top">内容1版块</div>
<div className={style.bg_2} id="center">内容2版块</div>
<div className={style.bg_3} id="foor">内容3版块</div>