[英]How to render images dynamically to React Carousel?
I'm trying to load images into React Carousel.我正在尝试将图像加载到 React Carousel 中。 When I .map through the array of filepaths for my images, I load all the images into one 'slide', but I need them to load into different slides.
当我对图像的文件路径数组进行 .map 映射时,我将所有图像加载到一个“幻灯片”中,但我需要将它们加载到不同的幻灯片中。
Seen (all four pictures in one slide):看过(一张幻灯片中的所有四张图片):
Wanted (note the 4 dots at bottom, indicating 4 slides. This example is just hard-coded):通缉(注意底部的 4 个点,表示 4 张幻灯片。这个例子只是硬编码):
Here's the relevant code.这是相关的代码。 Item.js is the parent and CarouselImages.js is the imported function to parse.
Item.js 是父级,CarouselImages.js 是要解析的导入函数。 There's a lot more to these components but I pared them down to the necessary parts.
这些组件还有很多,但我将它们缩减为必要的部分。
Item.js项目.js
import React from 'react';
import Carousel from 'react-elastic-carousel'
import CarouselImages from 'components/DatabaseManager/HelperFunctions/CarouselImages.js'
import {
Col,
Row,
CarouselItem
} from 'reactstrap'
class Item extends React.Component {
constructor(props) {
super(props)
this.state = {
activeContent: "item",
}
}
..
render() {
return (
<div>
<Row>
<Col md="6">
<Carousel itemsToShow={1}>
<CarouselImages data={this.props.data} />
</Carousel>
</Col>
</Row>
</div>
)
}
}
export default Item;
Hard-coded Item.js that works:有效的硬编码 Item.js:
...
<Carousel itemsToShow={1}>
<item><img src={require(`assets/img/phones/i5BlackScreenFront.jpg`)} alt="phone" /></item>
<item><img src={require(`assets/img/phones/i5BlackScreenBack.jpg`)} alt="phone" /></item>
<item><img src={require(`assets/img/phones/i5WhiteScreenFront.jpg`)} alt="phone" /></item>
<item><img src={require(`assets/img/phones/i5WhiteScreenBack.jpg`)} alt="phone" /></item>
</Carousel>
...
CarouselImages.js: CarouselImages.js:
import React from 'react';
export default function CarouselImages({ data }) {
return (
data.photoPath.map((image) => {
return <item><img src={require(`assets/img/${image}`)} alt="phone" /></item>
})
)
}
data prop (from API call):数据道具(来自 API 调用):
{
"photoPath": [
"phones/i5BlackScreenFront.jpg",
"phones/i5BlackScreenBack.jpg",
"phones/i5WhiteScreenFront.jpg",
"phones/i5WhiteScreenBack.jpg"
]
}
Your CarouselImages component is returning as one group which is why they are all appearing on the same slide.您的 CarouselImages 组件作为一组返回,这就是为什么它们都出现在同一张幻灯片上。 If you want to split it up into a separate component like this, you should change CarouselImages.js to
如果你想把它拆分成这样一个单独的组件,你应该把 CarouselImages.js 改为
import React from 'react';
export default function CarouselImages({ data }) {
return (
<Carousel itemsToShow={1}>
{data.photoPath.map((image) => {
return <item><img src={require(`assets/img/${image}`)} alt="phone" /></item>}
</Carousel>
})
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.