如何在next js Image中使用动态链接?

Kou*_*aha 4 javascript reactjs next.js nextjs-image

我想在下一个js中使用动态链接Image。接下来Js建议

<Image
        src="/me.png"
        alt="Picture of the author"
        width={500}
        height={500}
      />
Run Code Online (Sandbox Code Playgroud)

但我想用像

const imageDynamic = [Image][1]
Run Code Online (Sandbox Code Playgroud)
<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}
      />
Run Code Online (Sandbox Code Playgroud)

图像将来自 api,因此图像 src 每次都会更改。我无法在下一个js图像中使用链接,是否可以在下一个js图像中使用链接?

Pab*_*sky 5

Next Image 的工作方式与 html 标签类似img。对于动态用例,您应该将动态数据获取到页面。

要获取动态数据,您应该使用getServerSidePropsgetStaticProps通过 url 传递动态道具: https: //nextjs.org/docs/basic-features/data-fetching

import Image from "next/image";

const WithDynamicImage = ({image}) => {

return (
    <Image src={image}
      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;
Run Code Online (Sandbox Code Playgroud)

数据获取仅适用于pages/文件夹,不适用于组件。如果您要在组件中使用,您应该获取页面中的数据并将 prop 传递到组件中。