如何通过API动态更新SVG组件内的图片
Solution: Dynamically Set SVG Image Source from API Data
Here's how to adjust your code to pull image URLs from your API response and pass them to your SVG component:
Step 1: Update the SVG Component to Accept Dynamic Image Props
First, modify your SvgComponent to take an imageSrc prop instead of hardcoding the URL. We'll also use the modern href attribute instead of the deprecated xlinkHref (though if you're on an older React version, you can swap back to xlinkHref):
function SvgComponent({ imageSrc, ...props }) { return ( <svg xmlns="http://www.w3.org/2000/svg" width="3em" viewBox="0 0 850 1090" preserveAspectRatio="xMidYMid meet" height="3em" {...props} > <clipPath id="clip"> <path id="path" transform="translate(0,1090) scale(1,-1)" d="M406 1035 c-32 -49 -201 -104 -323 -105 l-43 0 0 -282 c0 -277 1 -284 24 -333 39 -82 146 -174 291 -250 l67 -34 61 31 c151 76 265 170 303 253 23 49 24 57 24 330 l0 281 -103 12 c-124 13 -206 42 -252 87 l-33 34 -16 -24z" /> </clipPath> {/* Use dynamic image source from props */} <image x={-200} y={30} width={1090} height={1090} clipPath="url(#clip)" href={imageSrc} /> <use href="#path" fill="none" stroke="gold" strokeWidth={30} /> </svg> ); }
Step 2: Pass API Data to the SVG Component
In your Map component, pass the image URL from each API entry to SvgComponent. Make sure to use a unique key (preferably an ID from your data) for list items:
export default function Map({ posts }) { return ( <> {posts && posts.map((mapItem) => ( // Replace 'imageUrl' with the actual key from your API response (e.g., 'src', 'url') <SvgComponent key={mapItem.id} // Use a unique ID from your data instead of index if possible imageSrc={mapItem.imageUrl} /> ))} </> ); }
Key Notes:
- API Response Structure: Ensure your
http://localhost:1337/mapsAPI returns objects with an image URL field (likeimageUrl,src, orurl). AdjustmapItem.imageUrlto match the exact key from your data. - Deprecated
xlinkHref: Modern SVG and React versions usehrefinstead ofxlinkHref. If you're working with an older React setup, replacehrefwithxlinkHrefin both the<image>and<use>tags. - List Keys: Always include a unique
keyprop when rendering lists in React to avoid performance issues and warnings. Use a unique identifier from your API data (likemapItem.id) instead ofindexif your list might reorder.
Working getStaticProps (unchanged)
Your existing data fetching code is fine—just make sure the API returns the image URLs you need:
export async function getStaticProps() { const res = await fetch("http://localhost:1337/maps"); const posts = await res.json(); return { props: { posts }, }; }
内容的提问来源于stack exchange,提问作者JJM50
相关产品推荐
相关产品推荐

