【问题标题】:React-Bootstrap carousel slider: how to detect current slide in displayReact-Bootstrap 轮播滑块:如何检测显示中的当前幻灯片
【发布时间】:2021-04-06 14:58:39
【问题描述】:

我有一个引导滑块(通过库:React-Bootstrap)并且想找到一种方法来检测当前显示的幻灯片(通过类代码而不是钩子)。这是 Slider 组件:

//import image1, image2, image3

class HeroSlider extends Component {

  handleSelect(){
    console.log('this sets the slide, but I just want to know the index of current slide')
  }

  render(){
  return (
    <Carousel indicators={false} controls={false} pause={false} onSelect={this.handleSelect()}>
      <Carousel.Item>
        <img className="d-block w-100" src={image1} alt="First slide" />
      </Carousel.Item>
      <Carousel.Item>
        <img className="d-block w-100" src={image2} alt="Third slide" />
      </Carousel.Item>
      <Carousel.Item>
        <img className="d-block w-100" src={image3} alt="Third slide" />
      </Carousel.Item>
    </Carousel>
  );
      }
}

export default HeroSlider

我该怎么办?谢谢。

【问题讨论】:

  • 您必须将轮播设为受控组件,并在状态下跟踪活动索引。请参阅文档:react-bootstrap.github.io/components/carousel/#controlled
  • 我看到了文档,但可能是因为我不擅长钩子,我能从中得到的只是你可以使用activeIndexonSelect 设置索引。如果您可以在此处发布有关如何通过状态跟踪幻灯片(使用 activeIndex 和/或 onSelect)以及使用基于类的组件的问题,我将非常感激

标签: reactjs slider react-bootstrap bootstrap-carousel


【解决方案1】:

我也建了一个,并将它用于索引:

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

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

要检测当前幻灯片的样式,您可以使用 class="active carousel-item"。

【讨论】:

  • 谢谢,但我想检测活动类以设置其他样式,所以我想通过代码检测它(当某个幻灯片可见时,调用一个在道具中传递的函数,即将为另一个元素设置样式)。所以通过 CSS 检测它不会有帮助
【解决方案2】:

好的,我是这样解决的:

react-bootstrap carousel 提供的功能/属性无助于检测幻灯片索引的变化,它们只允许您设置它。

我想要一个图像背景滑块,它可以无限旋转,同时在每个图像处停止 3 秒。所以我最终只是使用间隔函数将状态设置为每 3 秒更新一次索引。代码如下:

class HeroSlider extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      index: 0,
    };
  }
  componentDidMount() {
    this.interval = setInterval(
      () => this.setState({ index: (this.state.index + 1) % 7 }), 
      3000
    );
  }
  componentWillUnmount() {
    clearInterval(this.interval);
  }

  render(){
  return (
    <Carousel indicators={false} controls={false} pause={false} onSelect={this.handleSelect()}>
      <Carousel.Item>
        <img className="d-block w-100" src={image1} alt="First slide" />
      </Carousel.Item>
      <Carousel.Item>
        <img className="d-block w-100" src={image2} alt="Third slide" />
      </Carousel.Item>
      <Carousel.Item>
        <img className="d-block w-100" src={image3} alt="Third slide" />
      </Carousel.Item>
    </Carousel>
  );
      }
}

export default HeroSlider

现在,如果我想检测当前滑块索引,我只需访问 this.state.index。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 2016-08-22
    相关资源
    最近更新 更多