React Bootstrap旋转木马在滑动时向上滚动



当我滑到下一个或上一个项目时,我正试图弄清楚如何使Reactstrap转盘向上滚动。

这正是我需要它的工作方式Bootstrap旋转木马滑动时滚动顶部但我使用reactstrap节点模块以另一种方式进行操作,我不太清楚如何使window.scrollTo(0,0)之类的东西与下一个和上一个幻灯片按钮相关。

代码如下:

import React, { useState, Component } from 'react';
import fotos2 from '../data/fotos2'
import {
Carousel,
CarouselItem,
CarouselControl,
CarouselIndicators,
CarouselCaption
} from 'reactstrap';
const Example = (props) => {
const [activeIndex, setActiveIndex] = useState(props.id);
const [animating, setAnimating] = useState(false);
const scrollTop = () => {
window.scrollTo(0,0);
};
const next = () => {
if (animating) return;
const nextIndex = activeIndex === fotos2.length - 1 ? 0 : activeIndex + 1 || 
setActiveIndex(nextIndex);
scrollTop();
}
const previous = () => {
if (animating) return;
const nextIndex = activeIndex === 0 ? fotos2.length - 1 : activeIndex - 1;
setActiveIndex(nextIndex);
scrollTop();
}
const goToIndex = (newIndex) => {
if (animating) return;
setActiveIndex(newIndex);
}
const slides = fotos2.map((item) => {

return (
<CarouselItem data-pause="hover" style={{ minHeight: '20em' }}
className="custom-tag"
tag="div"
key={item.url}
onExiting={() => setAnimating(true)}
onExited={() => setAnimating(false)}
>
{/* <img src={props.foto} alt={item.altText}/> */}
<img className="imagenCarousel" src={item.url} alt={item.altText} />
<CarouselCaption className="text-danger" captionText={item.caption} captionHeader={item.caption} />
</CarouselItem>

);
});
return (
<div>
{/* interval={false} para el slider */}
<Carousel
activeIndex={activeIndex}
next={next}
previous={previous}
interval={false}
>
<CarouselIndicators items={fotos2} activeIndex={activeIndex} onClickHandler={goToIndex} />
{slides}
<CarouselControl direction="prev" directionText="Previous" onClickHandler={previous} />
<CarouselControl direction="next" directionText="Next" onClickHandler={next} />
</Carousel>
</div>
);
}
export default Example;

我已经尝试了几种解决方案,但它使主窗口向上滚动,而不是只滚动包含转盘的Modal

提前感谢您抽出时间!

每次更改activeIndex时都需要调用useEffect才能将元素滚动到顶部。试试这个,让我知道它是否有效。。

useEffect(()=>{window.scrollTop(0);},[activeIndex])

如果您阅读文档,您将看到scrollTo接受2个参数(x,y(或1个对象类型的参数。使用window.scrollTo(0);将导致错误,因为它既没有传递对象也没有传递2个参数。

您可以通过为y轴添加第二个参数来解决此问题:

const scrollTop = () => {
window.scrollTo(0, 0);
};

此外,当调用nextprevious时,您当前实现的向右上滚动将立即将窗口滚动到右上。如果你想保留你链接的堆栈溢出问题的行为(即,动画完成后滚动到顶部(,你可以选择触发CarouselItem组件的onExited道具回调上的scrollTop函数

<CarouselItem
onExited={() => {
setAnimating(false);
scrollTop();
}}
></CarouselItem>

CodeSandBox:https://codesandbox.io/s/heuristic-bird-n2vno?file=/src/App.js


模式溢出问题的概念和逻辑相同。这一次您可以使用Element.scroll,其中Element是对模式可滚动DOM元素的React引用。

const containerRef = useRef(null);
const scrollTop = () => {
// window.scrollTo(0, 0);
containerRef.current.scroll(0, 0);
};
<div ref={containerRef}>

CodeSandBox:https://codesandbox.io/s/relaxed-mclaren-sklgp?file=/src/App.js

useRef挂钩:https://reactjs.org/docs/hooks-reference.html#useref

最新更新