【发布时间】:2022-12-11 09:28:28
【问题描述】:
我是尝试学习 React 的编码新手,所以这是我的问题:
我的数据文件
import Car1 from '../../img/car1.jpg'
import Car2 from '../../img/car2.jpg'
const carsData = [
{
id: '1',
image: [Car1, Car1, Car1, Car1],
price: '$80 000',
},
{
id: 2,
image: [Car2, Car2, Car2, Car2],
},
]
我的产品详情页面
import React, { useState } from "react";
import "./CarProductDetails.css";
import "swiper/css";
import "swiper/css/free-mode";
import "swiper/css/navigation";
import "swiper/css/thumbs";
import { Swiper, SwiperSlide } from "swiper/react";
import { FreeMode, Navigation, Thumbs } from "swiper";
import carsData from "../data/CarsData";
import { useParams } from "react-router-dom";
const CarProductDetails = () => {
const [thumbsSwiper, setThumbsSwiper] = useState(null);
const { productId } = useParams();
const thisProduct = carsData.find((product) => product.id === productId);
return (
<>
<Swiper
style={{
"--swiper-navigation-color": "#fff",
"--swiper-pagination-color": "#fff",
}}
loop={true}
spaceBetween={10}
navigation={true}
thumbs={{ swiper: thumbsSwiper }}
modules={[FreeMode, Navigation, Thumbs]}
className="mySwiper2"
>
{/* I want to render each image from data array to each SwiperSlide */}
<SwiperSlide>
<img src={thisProduct.image} />
</SwiperSlide>
</Swiper>
<Swiper
onSwiper={setThumbsSwiper}
spaceBetween={5}
slidesPerView="4"
freeMode={true}
watchSlidesProgress={true}
allowTouchMove={false}
modules={[FreeMode, Navigation, Thumbs]}
className="mySwiper"
>
{/* Same here - it's a thumbnail images */}
<SwiperSlide>
<img src={thisProduct.image} />
</SwiperSlide>
</Swiper>
</>
);
};
export default CarProductDetails;
我想将数据 img 数组中的每个图像渲染为新的 SwiperSlide
我找到的解决方案是为每个图像写下 SwiperSlide 并在其中放入索引。
<SwiperSlide>
<img src={thisProduct.image[0]} />
</SwiperSlide>
<SwiperSlide>
<img src={thisProduct.image[1]} />
</SwiperSlide>
<SwiperSlide>
<img src={thisProduct.image[2]} />
</SwiperSlide>
<SwiperSlide>
<img src={thisProduct.image[3]} />
</SwiperSlide>
它确实有效,但如果我的数据文件中每个对象的图像数量不同(obj1 - 5 张图像,obj2 - 6 张图像?
这个问题最好的解决方案是什么?
【问题讨论】:
标签: javascript html css reactjs react-native