You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Bootstrap轮播:如何在独立列显示对应图片描述

解决方案:跟踪React Bootstrap Carousel当前索引并显示对应描述

实现需求只需三步:

  • 用useState维护当前轮播图的索引状态
  • 给Carousel组件绑定onSelect回调,更新当前索引
  • 根据当前索引在右侧列渲染对应图片的描述

修改后的完整代码如下:

import Carousel from 'react-bootstrap/Carousel';
import './style.css'
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import { useState } from 'react';

function App(props) {
  // 维护当前活动轮播项的索引,初始为0
  const [currentIndex, setCurrentIndex] = useState(0);

  // 轮播切换时更新索引
  const handleCarouselSelect = (selectedIndex) => {
    setCurrentIndex(selectedIndex);
  };

  return (
    <Container>
      <Row>
        <Col>
          <Carousel 
            className='mycarousel'
            onSelect={handleCarouselSelect} // 绑定切换回调
            activeIndex={currentIndex} // 同步当前活动索引
          >
            {props.adem.map((element, index) => (
              <Carousel.Item key={element.id} id={element.id}>
                <img
                  className="myImage"
                  src={element.images.url[0]}
                  alt={`Slide ${index + 1}`}
                />
              </Carousel.Item>
            ))}
          </Carousel>
        </Col>

        <Col>
          {/* 根据当前索引渲染对应描述 */}
          {props.adem[currentIndex] && (
            <div>
              <h3>{props.adem[currentIndex].title}</h3>
              <p>{props.adem[currentIndex].description}</p>
            </div>
          )}
        </Col>
      </Row>
    </Container>
  );
}

export default App;

关键说明:

  • onSelect是React Bootstrap Carousel内置的回调,轮播项切换时触发,参数selectedIndex即为当前选中项的索引
  • 设置activeIndex={currentIndex}确保组件状态与轮播的实际选中状态同步
  • 右侧列通过props.adem[currentIndex]获取当前项数据,示例中假设数据包含title和description字段,可根据你的实际字段名调整

内容的提问来源于stack exchange,提问作者GreatGig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 20:40:30