import React, { useState } from 'react';
import styles from './index.less';
const ImageSwitch = (props) => {
// 传入图片的大小,及图片 图片是数组的形式
const { width = 150, height = 150, picList = [] } = props;
const [picIndex, setPicIndex] = useState(1); // 当前图片展示的是第几页,默认为第一页图片
const [currentPicList, setCurrentPicList] = useState(picList.filter((item, index) => index < 4)); // 当前展示的图片
// 向左走
const turnLeft = () => {
if (picIndex > 1) {
setPicIndex(picIndex - 1);
setCurrentPicList(picList.filter((item, index) => index >= ((picIndex - 2) * 4) && index < ((picIndex - 1) * 4)));
}
};
// 向右走
const turnRight = () => {
if (picIndex < picList.length / 4) {
setPicIndex(picIndex + 1);
setCurrentPicList(picList.filter((item, index) => index < ((picIndex + 1) * 4) && index >= (picIndex * 4)));
}
};
return (
<div className={styles.root}>
<div className={styles.wrap}>
<div style={{ lineHeight: `${height}px` }} className={styles.arrow} onClick={turnLeft}><</div>
{/* {
currentPicList.map((item, index) => (
<img src={item} width={width} height={height} key={index} />
))
} */}
{
(picIndex - 1) * 4 < picList.length ? (
<img src={currentPicList[0]} width={width} height={height} />
) : (<div style={{ width: `${width}px`, height: `${height}px` }} />)
}
{
(picIndex - 1) * 4 + 1 < picList.length ? (
<img src={currentPicList[1]} width={width} height={height} />
) : (<div style={{ width: `${width}px`, height: `${height}px` }} />)
}
{
(picIndex - 1) * 4 + 2 < picList.length ? (
<img src={currentPicList[2]} width={width} height={height} />
) : (<div style={{ width: `${width}px`, height: `${height}px` }} />)
}
{
(picIndex - 1) * 4 + 3 < picList.length ? (
<img src={currentPicList[3]} width={width} height={height} />
) : (<div style={{ width: `${width}px`, height: `${height}px` }} />)
}
<div style={{ lineHeight: `${height}px` }} className={styles.arrow} onClick={turnRight}>></div>
</div>
</div>
);
};
export default ImageSwitch;
.root{
.wrap{
display: flex;
.arrow{
cursor: pointer;
}
.arrow:nth-child(1) {
margin-right: 10px;
}
.arrow:last-child{
margin-left: 10px;
}
.arrow:hover{
background: rgba(0,0,0,0.06);
color:#0055FF;
}
}
}