gpt4 book ai didi

reactjs - 对滚动使用react

转载 作者:行者123 更新时间:2023-12-02 10:08:15 25 4
gpt4 key购买 nike

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

顶部菜单第一节第二节

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

我知道 this.sectionOne 是对内部引用的引用,对吧?但如何将其定向到“sectionOne.js”文件内的引用?

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

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

最佳答案

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

然后,在 Section1 内,

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

您可以看到一个工作示例 here

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

目前仅 React 16.3 支持前向引用,您可以使用 this alternative approach如果您需要较低版本的功能。

关于reactjs - 对滚动使用react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49831378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com