问题描述
我正在尝试将图像加载到React Carousel中。当我映射图像的文件路径数组时,我将所有图像加载到一张“幻灯片”中,但是我需要将它们加载到不同的幻灯片中。
想要的(请注意底部的4个点,指示4张幻灯片。此示例仅是硬编码的):
这是相关的代码。 Item.js是父级,而CarouselImages.js是要解析的导入函数。这些组件还有很多,但我将它们缩减为必要的部分。
Item.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;
有效的硬编码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:
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>
})
)
}
数据道具(通过API调用):
{
"photoPath": [
"phones/i5BlackScreenFront.jpg","phones/i5BlackScreenBack.jpg","phones/i5WhiteScreenFront.jpg","phones/i5WhiteScreenBack.jpg"
]
}
解决方法
您的CarouselImages组件将作为一组返回,这就是为什么它们都出现在同一张幻灯片上的原因。如果您希望将其拆分成这样的单独组件,则应将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>
})
)
}