有什么问题。我有一个传送带和不能位于传送带内的按钮。我如何将它们与轮播连接?在 React-Bootstrap 网站上,他们建议使用 activeIndex,但在这种情况下,轮播不像标准按钮那样循环。在最后一张图像之后,该按钮只会将您返回到开头,而不是在最后一张图像之后显示第一张图像。我也可以将组件粘贴到 prevIcon 和 nextIcon 中,但按钮位于轮播内部,而不是外部。
这是我的组件
/* eslint-disable jsx-a11y/control-has-associated-label */
import '../../styles/Banner/Banner.scss';
import Carousel from 'react-bootstrap/Carousel';
import { useState } from 'react';
import classNames from 'classnames';
import { Button } from '../Button';
export const Banner: React.FC = () => {
const [index, setIndex] = useState(0);
const handleSlideLeft = () => {
if (index === 0) {
setIndex(2);
} else {
setIndex(index - 1);
}
};
const handleSlideRight = () => {
if (index === 2) {
setIndex(0);
} else {
setIndex(index + 1);
}
};
return (
<section className="banner">
<div className="banner__carousel-container">
<Button
content="arrow"
arrowDirection="left"
onClick={handleSlideLeft}
/>
<Carousel
controls={false}
indicators={false}
activeIndex={index}
>
<Carousel.Item>
<img
src={example.png}
alt="phones"
className="banner__image"
/>
</Carousel.Item>
<Carousel.Item>
<img
src={example.png}
alt="tablets"
className="banner__image"
/>
</Carousel.Item>
<Carousel.Item>
<img
src={example.png}
alt="accessories"
className="banner__image"
/>
</Carousel.Item>
</Carousel>
<Button
content="arrow"
arrowDirection="right"
onClick={handleSlideRight}
/>
</div>
<div className="banner__badges">
<button
type="button"
className={classNames('banner__badge', {
active: index === 0,
})}
onClick={() => setIndex(0)}
/>
<button
type="button"
className={classNames('banner__badge', {
active: index === 1,
})}
onClick={() => setIndex(1)}
/>
<button
type="button"
className={classNames('banner__badge', {
active: index === 2,
})}
onClick={() => setIndex(2)}
/>
</div>
</section>
);
};
我看到你正在手动尝试,你可以做的是使用 React useRef 在自定义按钮中触发 corousal next,prev 。
const corousalRef = useRef(null);
const handleSlideLeft = () => {
corousalRef.current.prev();
};
const handleSlideRight = () => {
corousalRef.current.next();
};
const handleSelect = (selectedIndex) => {
setIndex(selectedIndex);
};
...
<Carousel
activeIndex={index}
onSelect={handleSelect}
controls={false}
indicators={false}
ref={corousalRef}
>
...