ReactJS:如何水平展示SVG数组且保持尺寸恒定?
解决SVG水平排列且保持固定尺寸的问题
核心解决思路
给SVG设置固定宽高,并禁止flex容器压缩它,就能确保无论元素数量增减,SVG尺寸都保持不变。
修改后的完整代码
import { useState } from "react"; import "./styles.css"; export default function App() { const [states, setStates] = useState([0, 0, 0, 0, 0]); // 用于测试的添加/移除元素方法 const addSVG = () => setStates([...states, 0]); const removeSVG = () => setStates(states.slice(0, -1)); return ( <div> <div style={{ marginBottom: "1rem" }}> <button onClick={addSVG}>添加SVG</button> <button onClick={removeSVG} style={{ marginLeft: "0.5rem" }}>移除SVG</button> </div> <div style={{ display: "flex", gap: "0.5rem", overflowX: "auto" }}> {states.map((state, stateIndex) => ( <svg key={stateIndex} viewBox="0 0 100 35" width="25" height="25" style={{ flexShrink: 0 }} > <rect fill={"black"} width={"25"} height={"25"} /> </svg> ))} </div> </div> ); }
关键修改点说明
width="25"和height="25":直接给SVG指定固定显示尺寸,明确其渲染大小。flexShrink: 0:阻止flex容器在空间不足时压缩SVG,保证尺寸稳定。key={stateIndex}:React列表渲染必须添加唯一key,避免渲染异常。overflowX: "auto":当SVG数量过多超出容器宽度时,自动显示横向滚动条,避免布局错乱。gap: "0.5rem":给SVG之间添加间距,优化布局美观度。
内容的提问来源于stack exchange,提问作者bascott
相关产品推荐
相关产品推荐

