反应滚动到组件

Mad*_*ads 2 scroll reactjs

我有 3 个组件,这是我的网站。加载每个组件 js 文件,并且所有 3 个组件都显示在一个页面上,如下所示:

Topmenu SectionOne SectionTwo

在 Topmenu 组件中,我只有一个菜单。我试图在菜单字段 (SectionOne) 上设置 scrollToComponent onClick。但是我不知道如何让它在点击时滚动到 SectionOne?

我知道 this.sectionOne 是对内部引用的引用,对吗?但是如何将它指向“sectionOne.js”文件中的一个引用呢?

我的 TopMenu.js 文件中有以下内容

     onClick={() => scrollToComponent(this.sectionOne , { offset: 0, align: 'top', duration: 1500})}
Run Code Online (Sandbox Code Playgroud)

Agn*_*ney 5

要将 转发ref到组件内部的某个位置,您可以使用forwardRef.

这意味着我们在父组件中创建 ref 并将其传递给组件,组件将其传递给其中的 DOM 元素。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.section1 = React.createRef();
    this.section2 = React.createRef();
    this.scrollToContent = this.scrollToContent.bind(this);
  }
  scrollToContent(content) {
    switch(content) {
      case 1:
        this.section1.current.scrollIntoView({behavior: 'smooth'});
        break;
      case 2:
        this.section2.current.scrollIntoView({behavior: 'smooth'});
    }
  }
  render() {
    return (
      <main>
        <Menu goTo={this.scrollToContent} />
        <div className='main'>
          <Section1 ref={this.section1} />
          <Section2 ref={this.section2} />
        </div>
      </main>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,在里面Section1

const Section1 = React.forwardRef((props, ref)=>{
  return (
    <section ref={ref} className='section'>
      <p>Section 1</p>
    </section>
  );
});
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看工作示例

我没有使用scroll-to-component包,但同样的事情也适用。

Forward Refs 现在仅在 React 16.3 中受支持,如果您在较低版本中需要该功能,则可以使用这种替代方法