React中创建固定尺寸响应式矩阵:Flexbox/Grid哪种方案更优?
React 实现窗口 resize 时行列尺寸固定的矩阵方案
方案1:固定像素尺寸 + 容器滚动(最直接)
直接给矩阵单元格设置固定像素的宽高,外层容器开启滚动。窗口大小变化时,单元格尺寸完全不变,容器会自动出现滚动条适配窗口。推荐用Grid布局实现,它天生适配二维矩阵场景,比Flexbox更易控制行列规则。
import React from 'react'; const FixedSizeMatrix = () => { const rowCount = 5; const colCount = 5; const cellSize = 120; // 固定单元格尺寸 return ( <div style={{ width: '100vw', height: '100vh', overflow: 'auto', padding: '10px', boxSizing: 'border-box' }} > <div style={{ display: 'grid', gridTemplateColumns: `repeat(${colCount}, ${cellSize}px)`, gridTemplateRows: `repeat(${rowCount}, ${cellSize}px)`, gap: '4px' }} > {Array.from({ length: rowCount * colCount }).map((_, idx) => ( <div key={idx} style={{ width: `${cellSize}px`, height: `${cellSize}px`, backgroundColor: '#f5f5f5', border: '1px solid #ddd', display: 'flex', alignItems: 'center', justifyContent: 'center' }} > 单元格 {idx + 1} </div> ))} </div> </div> ); }; export default FixedSizeMatrix;
方案2:自适应行列数 + 固定单元格尺寸
如果需要窗口变化时,自动调整矩阵的行列数量(但单元格尺寸不变),可以监听窗口resize事件,计算容器能容纳的行列数。
import { useState, useEffect } from 'react'; const AdaptiveFixedCellMatrix = () => { const cellSize = 100; const [cols, setCols] = useState(0); const [rows, setRows] = useState(0); useEffect(() => { const updateMatrixSize = () => { // 计算可容纳的行列数(扣除容器内边距) const availableWidth = window.innerWidth - 30; const availableHeight = window.innerHeight - 30; setCols(Math.floor(availableWidth / cellSize)); setRows(Math.floor(availableHeight / cellSize)); }; updateMatrixSize(); window.addEventListener('resize', updateMatrixSize); return () => window.removeEventListener('resize', updateMatrixSize); }, [cellSize]); return ( <div style={{ width: '100%', height: '100vh', padding: '15px', boxSizing: 'border-box' }} > <div style={{ display: 'grid', gridTemplateColumns: `repeat(${cols}, ${cellSize}px)`, gridTemplateRows: `repeat(${rows}, ${cellSize}px)`, gap: '3px', backgroundColor: '#eee' }} > {Array.from({ length: cols * rows }).map((_, idx) => ( <div key={idx} style={{ width: `${cellSize}px`, height: `${cellSize}px`, backgroundColor: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }} > {idx + 1} </div> ))} </div> </div> ); }; export default AdaptiveFixedCellMatrix;
为什么Flexbox百分比方案没达到预期?
Flexbox是一维布局,子元素的百分比尺寸是相对于父容器的可用空间。窗口变化时父容器宽度改变,子元素会跟着缩放。而Grid的repeat(${cols}, ${size}px)是直接固定每列/每行的绝对尺寸,不会随父容器空间变化,更贴合固定行列尺寸的需求。
内容的提问来源于stack exchange,提问作者Harshit Gupta
相关产品推荐
相关产品推荐

