reactjs - 如何在 React 中为每个关闭的手风琴选项卡添加滚动到顶部动画?
问题描述
我想做一个手风琴,当你点击关闭手风琴(默认打开)时,主要关闭的手风琴滚动到页面顶部,使其到页面顶部,下一个打开的手风琴是焦点观点。到目前为止,我可以让手风琴关闭并滚动到顶部,但他们都这样做了,所以它只是一直向下滚动到页面底部。
一个例子:这里
到目前为止我所做的:这里
我已经尝试过 react-scroll-to-component、scroll-to 和其他一些
scrollToTop = () => {
let scroller = scrollToComponent(this.index, {
offset: 0,
align: "top",
duration: 1000,
ease: "inExpo"
});
scroller.on("end", () => console.log("Scrolling End!"));
};
render() {
return (
<div className='news'>
{this.state.news.map((newbie, index) => {
return (
<div key={index} className='news_info' id={`news_info-${index}`}>
<Accordion defaultActiveKey={index}>
<Card>
<Card.Header>
<p>{newbie.title}</p>
<Accordion.Toggle
as={Button}
variant='link'
eventKey={index}
onClick={this.scrollToTop}
>
+
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse
eventKey={index}
ref={section => {
this.index = section;
}}
>
<Card.Body>
<img src={newbie.image} />
<p>{newbie.details}</p>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
</div>
);
})}
</div>
);
}
}
解决方案
我认为问题是,您ref
为每个collapsiable
. 您需要为您ref
的.index
map
你的代码应该是这样的,
scrollToTop = (index) => {
let scroller = scrollToComponent(this['section-'+index], { //use passed index to scroll exact collapsiable
offset: 0,
align: "top",
duration: 1000,
ease: "inExpo"
});
scroller.on("end", () => console.log("Scrolling End!"));
};
render() {
return (
<div className='news'>
{this.state.news.map((newbie, index) => {
return (
<div key={index} className='news_info' id={`news_info-${index}`}>
<Accordion defaultActiveKey={index}>
<Card>
<Card.Header>
<p>{newbie.title}</p>
<Accordion.Toggle
as={Button}
variant='link'
eventKey={index}
onClick={() => this.scrollToTop(index)} //pass index here
>
+
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse
eventKey={index}
ref={section => {
this['section-'+index] = section; //dynamic ref
}}
>
<Card.Body>
<img src={newbie.image} />
<p>{newbie.details}</p>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
</div>
);
})}
</div>
);
}
}
推荐阅读
- python - 如何使用 pyPDF2 从 PDF 格式的多页简历中提取文本数据?
- codenameone - 代号一已购买证书,但无法继续
- javascript - Jquery在选择元素上添加一个空行
- css - 避免中间标签干扰 display:table
- android - 无法为 org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler 类型的对象获取未知属性“FCM_VERSION”
- uwp - 在离线计算机上设置 UWP 程序的最简单方法是什么?
- angular - 如何为 Angular 5 安装 if-media 模块
- c++ - 使用堆栈分配的复合对象调用 C++ 析构函数两次
- ios - iOS RxSwift 如何防止序列被处理(抛出错误)?
- makefile - Linux 内核项目是否使用一些构建自动化软件来创建他们的 makefile?