我想在下一个 js Image
中使用动态链接。
接下来Js建议
<Image
src="/me.png"
alt="Picture of the author"
width={500}
height={500}
/>
但是我想用like
const imageDynamic = [Image][1]
<Image
src="https://en.wikipedia.org/wiki/Image#/media/File:Image_created_with_a_mobile_phone.png" or {imageDynamic}
alt="Picture of the author"
width={500}
height={500}
/>
图像将来自 api,因此图像 src 每次都会更改。我不能在下一个 js 图像中使用链接,是否可以在下一个 js 图像中使用链接?
最佳答案
Next 图像的工作方式类似于 html img
标签。对于动态用例,您应该将动态数据提取到页面。
要获取动态数据,您应该使用 getServerSideProps
或 getStaticProps
通过 url 传递动态属性:
https://nextjs.org/docs/basic-features/data-fetching
import Image from "next/image";
const WithDynamicImage = (image) => {
return (
<Image src={imageDynamic}
alt="Picture of the author"
width={500}
height={500}
/>
)
}
export async function getServerSideProps({
params,
}) {
const image = await getImages() // fetch your data;
const imageDynamic = image[param.id] //pass the prop from the url
return { props: { image : imageDynamic || null } };
}
export default WithDynamicImage;
数据获取仅适用于 pages/
文件夹,不适用于组件。如果您要使用 into 组件,您应该在页面中获取数据并将 prop 传递到组件中。
关于javascript - 如何在下一个js图像中使用动态链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66756073/