【问题标题】:How to control react-bootstrap carousel with custom buttons?如何使用自定义按钮控制 react-bootstrap 轮播?
【发布时间】:2021-07-31 05:41:37
【问题描述】:

在这里,我需要使用自定义按钮来控制轮播幻灯片,这是在 Example 的帮助下实现的。

这是它的代码..

import React, { useState } from "react";
import { Carousel, Button, Container, Row } from "react-bootstrap";
import Cards from "../cards";
import "./slider.css";

const Slider = () => {
  const [index, setIndex] = useState(0);

  const handleSelect = (selectedIndex, e) => {
    setIndex(selectedIndex);
  };

  const onPrevClick = () => {
    if (index > 0) {
      setIndex(index - 1);
    } else if (index === 0) setIndex(2);
  };
  const onNextClick = () => {
    if (index === 2) {
      setIndex(0);
    } else if (index === 0 || index > 0) setIndex(index + 1);
  };

  return (
    <>
      <div className="button-container">
        <Container>
          <Row>
            <Button variant="primary" onClick={onPrevClick}>
              Previous
            </Button>
            <Button variant="primary" onClick={onNextClick}>
              Next
            </Button>
          </Row>
        </Container>
      </div>
      <Carousel
        activeIndex={index}
        onSelect={handleSelect}
        indicators={false}
        controls={false}
      >
        <Carousel.Item>
          <Cards />
        </Carousel.Item>
        <Carousel.Item>
          <Cards />
        </Carousel.Item>
        <Carousel.Item>
          <Cards />
        </Carousel.Item>
      </Carousel>
    </>
  );
};

export default Slider;

但是当活动索引在最后一个项目中时,这意味着在最后一个轮播幻灯片中。当我按下下一个按钮时,它会从最后一个旋转木马一直移动到第一个旋转木马,即方向就像 3 -> 2 -> 1。

我知道我在 onClick 函数中做了一些糟糕的逻辑。因此,我正在寻求帮助,向我建议使用自定义按钮控制轮播幻灯片的最佳方法,非常感谢您的帮助。请查看我的代码并告诉我任何建议。提前致谢。

这里是code sandbox link

【问题讨论】:

    标签: javascript reactjs bootstrap-4 react-hooks react-bootstrap


    【解决方案1】:

    使用ref property 您可以控制prevnext 操作

      const ref = useRef(null);
    
      const onPrevClick = () => {
        ref.current.prev();
      };
      const onNextClick = () => {
        ref.current.next();
      };
    

    JSX

      <Carousel
        ref={ref}
        ...
      >
    

    【讨论】:

      猜你喜欢
      • 2014-03-25
      • 2020-11-15
      • 1970-01-01
      • 2018-12-14
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 2013-03-28
      相关资源
      最近更新 更多