NextJS中SVG六边形组件传递图片Prop重复渲染问题求解
解决Next.js中HexagonTile组件重复渲染同一张图片的问题
在使用自定义HexagonTile组件渲染多个带不同图片的六边形时,所有六边形都显示第一个实例的图片,而非各自传入的图片。
问题原因
SVG元素的id在整个HTML文档中是全局唯一的。你的代码中每个HexagonTile组件的<pattern>都使用了固定的id="pattern0",当多个组件实例渲染时,后续的pattern0会覆盖之前的定义,但所有<path>的fill属性都指向#pattern0,最终导致所有六边形都使用第一个被定义的pattern0对应的图片。
解决方法
让每个组件实例的<pattern>拥有唯一的id,可以直接复用传入的imageId来命名pattern,确保每个path引用的是当前组件实例对应的pattern:
修改hexagon-tile.tsx的代码:
interface HexagonTileProp { imageLink: string, imageId: string } export default function HexagonTile({ imageLink, imageId }: HexagonTileProp) { // 用imageId生成唯一的pattern id const patternId = `pattern-${imageId}`; return ( <div> <svg height='387' viewBox='0 0 595 687' fill='none' xmlns='http://www.w3.org/2000/svg' xmlnsXlink='http://www.w3.org/1999/xlink'> {/* 引用当前组件的唯一pattern */} <path d='M297.5 0L594.98 171.75V515.25L297.5 687L0.0202637 515.25V171.75L297.5 0Z' fill={`url(#${patternId})`} /> <defs> {/* 使用唯一的pattern id */} <pattern id={patternId} patternContentUnits='objectBoundingBox' width='1' height='1'> <use xlinkHref={`#${imageId}`} transform='translate(-0.3) scale(0.000625)' /> </pattern> <image id={imageId} width='2560' height='1600' xlinkHref={imageLink} /> </defs> </svg> </div> ); }
原理说明
通过为每个组件实例生成唯一的patternId,确保每个<path>只引用当前组件内定义的<pattern>,避免了全局id冲突的问题,每个六边形就能正确渲染各自传入的图片了。
内容的提问来源于stack exchange,提问作者Kalindu Rithmal
相关产品推荐
相关产品推荐

