next.js 使用SVG作为react组件,使用图像链接作为 prop ?

k7fdbhmy  于 2023-08-04  发布在  React
关注(0)|答案(2)|浏览(111)

我正在尝试创建一个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>
  );
}

个字符
预期的结果应该在两个六边形内具有不同的图像。但这是实际的结果:


的数据

uplii1fm

uplii1fm1#

您应该自动生成图像和图案ID,或者将ID作为属性传入。您已经为每个图像/模式硬编码了它们,因此每个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

odopli94

odopli942#

您正在定义重复的模式ID。
使用id props修复它:

<svg viewBox="0 0 595 687">
  <path
    d="M297.5 0L594.98 171.75V515.25L297.5 687L0.0202637 515.25V171.75L297.5 0Z"
    fill={`url(#pattern${id})`}
  />
  <defs>
    <pattern
      id={`pattern${id}`}
      patternContentUnits="objectBoundingBox"
      width="1"
      height="1"
    >
      <use
        href={`#${id}`}
        transform="translate(-0.3) scale(0.000625)"
      />
      <image id={id} width="2560" height="1600" href={imageLink} />
    </pattern>
  </defs>
</svg>

字符串

相关问题