You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React如何实现每行3张、自动换行的自适应图片网格布局

解决方案

实现思路

使用Ant Design组件库的栅格系统完成布局,Ant Design的栅格默认将每行划分为24等分,给每个图片项分配8份宽度即可实现每行固定展示3项,超出自动换行的效果,该组件库完全适配React技术栈。

前置依赖

首先安装Ant Design组件库:

npm install antd

完整代码示例

import React from 'react';
import { Grid } from 'antd';

const { Row, Col } = Grid;

// 图片资源数组
const images = [
  {
    src: 'https://images.unsplash.com/photo-1509420316987-d27b02f81864?dpr=1&auto=format&fit=crop&w=1500&q=80&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D',
    width: 1500,
    height: 1000,
  },
  {
    src: 'https://images.unsplash.com/photo-1509641498745-13c26fd1ed89?dpr=1&auto=format&fit=crop&w=1000&q=80&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D',
    width: 666,
    height: 1000,
  },
  {
    src: 'https://images.unsplash.com/photo-1491146179969-d674118945ff?dpr=1&auto=format&fit=crop&w=1500&q=80&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D',
    width: 1500,
    height: 844,
  },
  {
    src: 'https://images.unsplash.com/photo-1509420316987-d27b02f81864?dpr=1&auto=format&fit=crop&w=1500&q=80&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D',
    width: 1500,
    height: 1000,
  },
  {
    src: 'https://images.unsplash.com/photo-1509641498745-13c26fd1ed89?dpr=1&auto=format&fit=crop&w=1000&q=80&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D',
    width: 666,
    height: 1000,
  }
];

const ImageGallery = () => {
  return (
    <div style={{ padding: 20 }}>
      <Row gutter={[16, 16]}>
        {images.map((item, index) => (
          <Col span={8} key={index}>
            <div style={{ width: '100%', height: 240, overflow: 'hidden' }}>
              <img 
                src={item.src} 
                alt={`图片${index+1}`}
                style={{ width: '100%', height: '100%', objectFit: 'cover' }}
              />
            </div>
          </Col>
        ))}
      </Row>
    </div>
  );
};

export default ImageGallery;

配置说明

  • gutter={[16,16]} 分别设置列之间的水平间距和行之间的垂直间距,可自行调整数值
  • span={8} 对应24栅格的1/3宽度,保证每行刚好展示3个项
  • 图片容器固定高度240px配合objectFit: cover保证所有图片展示高度一致,不会变形
  • 如果不需要固定高度可以去掉容器的height属性,让图片自适应原始比例展示

内容的提问来源于stack exchange,提问作者CoderInUi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 02:36:05