我正在参加「初夏创意投稿大赛」详情请看:初夏创意投稿大赛
夏日的风景总是那么多。也是旅游旺季,中国地广辽阔,风景众多。出去玩,当然是拍拍拍。
借助 Antd 组件库,可以十分快速地实现一个图片墙。100 行代码都不到哦~
假设我们的图片为二维数组
const imgs = [
['1.png', '2.png', '3.png', '4.png', '5.png'],
['6.png', '7.png', '8.png', '9.png', '10.png'],
['11.png', '12.png', '13.png', '14.png', '15.png'],
['16.png', '17.png', '18.png', '19.png', '20.png'],
['21.png', '22.png', '23.png', '24.png', '25.png']
]
栅格布局
使用单一的一组 Row 和 Col 栅格组件,就可以创建一个基本的栅格系统,所有列(Col)必须放在 Row 内。
栅格常常需要和间隔进行配合,可以使用 Row 的 gutter 属性。
import { Col, Row } from 'antd';
const App = () => (
<>
<Row>
<Col span={6}>col-6</Col>
<Col span={6}>col-6</Col>
<Col span={6}>col-6</Col>
<Col span={6}>col-6</Col>
</Row>
</>
);
export default App;
通过 Row 和 Col 进行页面布局
import React, { useState, useRef } from 'react'
import { Card, Row, Col, Modal, Carousel } from 'antd'
const Gallery = () => {
const imgList = imgs.map((list) => list.map((item) =>
<Card
style={{ marginBottom: 10 }}
cover={<img src={'/gallery/' + item} />}
>
<Card.Meta
title="图片"
description="夏季图片"
/>
</Card>
))
return (
<>
<Row gutter={10}>
<Col md={5}>
{imgList[0]}
</Col>
<Col md={5}>
{imgList[1]}
</Col>
<Col md={5}>
{imgList[2]}
</Col>
<Col md={5}>
{imgList[3]}
</Col>
<Col md={4}>
{imgList[4]}
</Col>
</Row>
</>
);
}
export default Gallery;
是不是超级方便呀~~~
当我们点击图片的时候,显示 Modal,中间放置我们的轮播图。
这里我们就需要用到 Antd 的 Modal 和 Carousel 组件。给图片添加一个 onClick 事件,使用 Carousel 的 goTo 方法。
import React, { useState, useRef } from 'react'
import { Card, Row, Col, Modal, Carousel } from 'antd'
const imgs = [
['1.png', '2.png', '3.png', '4.png', '5.png'],
['6.png', '7.png', '8.png', '9.png', '10.png'],
['11.png', '12.png', '13.png', '14.png', '15.png'],
['16.png', '17.png', '18.png', '19.png', '20.png'],
['21.png', '22.png', '23.png', '24.png', '25.png']
]
const Gallery = () => {
const [visible, setVisible] = useState(false);
const silder = useRef(null);
const openGallery = (item) => {
setVisible(true);
const _img = imgs.flat(Infinity);
const index = _img.findIndex((i) => i === item);
setTimeout(() => {
silder.current.goTo(parseInt(index));
}, 0);
}
const imgList = imgs.map((list) => list.map((item) =>
<Card
style={{ marginBottom: 10 }}
cover={<img src={'/gallery/' + item} onClick={() => openGallery(item)} />}
>
// ....
</Card>
))
return (
<>
// ....
<Modal
width={500}
height={600}
visible={visible}
title="图片画廊"
onCancel={() => {
setVisible(false);
}}
footer={null}
>
<Carousel autoplay ref={silder} infinite>
{
imgs.map((list) => list.map((item) =>
<img src={'/gallery/' + item} height={500} />
))
}
</Carousel>
</Modal>
</>
);
}
export default Gallery;
一共 78 代码。相当完美