在反应中实现平滑滚动

Implementing smooth scrolling in react

我正在尝试为自己创建一个网站,当您单击图片时,页面将向下滚动到不同部分中的另一个元素。

我现在的代码结构是我有一个应用程序 class 并且在其中 class 我制作了另外两个组件,将它们称为 A 和 B。

class App extends Component{
   render () { 
      return (<A/>
              <B/>)
}

用户点击的图像在组件 A 中,我想要滚动到的元素在 B 中。我尝试使用 element.scrollIntoView 函数通过创建一个 ref 来做到这一点:

class App extends Component{
    constructor(props){
        super(props);

        this.divToFocus = React.createRef();
    }
    

    handleOnClick = () =>{
        this.divToFocus.scrollIntoView({behavior: 'smooth'}
    }

    render () {
        return (
        <div>
            <A click={this.handleOnClick}/>
            <B name={this.divToFocus} />
        </div>)}

并在 A 中使用 handleOnClick 作为 img onClick 属性(确保为样式设置 "pointer-events": "all"),然后创建一个 div 并命名为 ref this.divToFocus 在 B 中,但出现类型错误,提示 this.divToFocus.scrollIntoView 不是函数。

我也尝试过使用 react-scroll 做这样的事情:

class A extends Component{
    render (){ 
        return (
        <Element name={"name"}>
            Hello world!
        </Element>
    )}
}

class B extends Component{
    render (){ 
        return (
        <Link activeClass="active" to="name" spy={true} smooth={true} offset={50} duration={500}>
          <img src={arrow} />
        </Link>
    )}
}

但是当我点击图片时没有任何反应。非常感谢有关如何执行此操作的任何建议!

您可以使用 DOM 和 ScrollIntoView 来实现。

A.js

import React from "react";

export default function A() {
  const handleImageClick = () => {
    document.getElementById("myid").scrollIntoView({ behavior: "smooth" });
  };
  return (
      <img
        onClick={handleImageClick}
        alt="placeholder"
        src="https://via.placeholder.com/728x200.png?text=Visit+WhoIsHostingThis.com+Buyers+GuideC/O https://placeholder.com/"
      />
  );
}

B.js

import React from "react";

export default function B() {
  return (
    <div id="myid">
      <h1>Hello CodeSandbox</h1>
      <h2>Some Long content for scroll to happen!</h2>
      <h2>Start editing to see some magic happen!</h2>
      <h2>Start editing to see some magic happen!</h2>
      <h2>Start editing to see some magic happen!</h2>
      <h2>Start editing to see some magic happen!</h2>
      <h2>Start editing to see some magic happen!</h2>
      <h2>Start editing to see some magic happen!</h2>
      <h2>Start editing to see some magic happen!</h2>
      <h2>Start editing to see some magic happen!</h2>
      <h2>Start editing to see some magic happen!</h2>
      <h2>Start editing to see some magic happen!</h2>
      <h2>Start editing to see some magic happen!</h2>
      <h2>Start editing to see some magic happen!</h2>
      <h2>Start editing to see some magic happen!</h2>

    </div>
  );
}

Codesandbox 演示 here