我正在尝试创建一个 react 组件(NextJS),它是一个内部有图像的六边形。该组件应该渲染作为 Prop 发送的图像。但是,当我尝试在 HeagonWall 中使用具有不同图像的多个组件时,所有六边形都会渲染该组件的第一个实例的图像,而不是相应地渲染两个图像。我该如何解决这个问题?
//hexagon-tile.tsx
interface HexagonTileProp {
imageLink: string,
imageId: string
}
export default function HexagonTile({ imageLink, imageId }: HexagonTileProp) {
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'>
<path d='M297.5 0L594.98 171.75V515.25L297.5 687L0.0202637 515.25V171.75L297.5 0Z' fill='url(#pattern0)' />
<defs>
<pattern id='pattern0' 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>
);
}
//hexagon-wall.tsx
export default function HexagonWall() {
return (
<div>
<HexagonTile imageLink='https://cdn.test.com/testimg/testimg-1.jpg' imageId={crypto.randomUUID()} />
<HexagonTile imageLink='https://cdn.test.com/testimg/testimg-2.jpg' imageId={crypto.randomUUID()} />
</div>
);
}
预期结果应该在两个六边形内有不同的图像。但这是实际结果:
最佳答案
您应该自动生成图像和图案 id,或者将 id 作为 prop 传入。您已经为每个图像/图案对它们进行了硬编码,因此每个 svg 将仅采用 DOM 中具有该 id 的第一个图像/图案。
您可以使用crypto.randomUUID()
生成唯一的ID。
注意此功能的支持:https://caniuse.com/mdn-api_crypto_randomuuid
注意xlink:href
is deprecated您只需使用href
即可。
export default function HexagonTile({ imageLink }: HexagonTileProp) {
const id = crypto.randomUUID();
const imageId = 'image' + id;
const useHref = '#' + imageId;
const patternId = 'pattern' + id;
const pathFill = 'url(#' + patternId + ')';
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"
>
<path
d="M297.5 0L594.98 171.75V515.25L297.5 687L0.0202637 515.25V171.75L297.5 0Z"
fill={pathFill}
/>
<defs>
<pattern
id={patternId}
patternContentUnits="objectBoundingBox"
width="1"
height="1"
>
<use href={useHref} transform="translate(-0.3) scale(0.000625)" />
</pattern>
<image id={imageId} width="2560" height="1600" href={imageLink} />
</defs>
</svg>
</div>
);
}
Stackblitz:https://stackblitz.com/edit/stackblitz-starters-vq1t45?file=src%2FApp.tsx
关于reactjs - 使用 SVG 作为 React 组件,并将图像链接作为 prop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76794097/