在 Gatsby 的 StaticImage 中使用动态外部 URL

Using dynamic external urls in StaticImage in Gatsby

我正在尝试显示包含图像 URL 的对象数组中的几张图像。我知道 StaticImage 必须接受局部变量作为道具值。图片 url 的这两个变量都是本地的。 为什么这不起作用,有解决方法吗?

import React from 'react';
import { StaticImage } from 'gatsby-plugin-image';

const TestPage = (props) => {
  const itemData = [
    {
      img: 'https://images.unsplash.com/photo-1549388604-817d15aa0110?w=161&fit=crop',
      title: 'Bed',
    },
    {
      img: 'https://images.unsplash.com/photo-1563298723-dcfebaa392e3?w=161&fit=crop',
      title: 'Kitchen',
    },
  ];

  const testSrc = 'https://images.unsplash.com/photo-1523413651479-597eb2da0ad6?w=161&fit=crop';
  const testSrc2 = itemData[0].img;

  return (
    <>
      <StaticImage src={testSrc} alt="works" />
      <StaticImage src={testSrc2} alt="doesn't" />
    </>
  )
}

export default TestPage;

正如你所说,有一个 restriction in the component:

Restrictions on using StaticImage

The images are loaded and processed at build time, so there are restrictions on how you pass props to the component. The values need to be statically-analyzed at build time, which means you can’t pass them as props from outside the component, or use the results of function calls, for example. You can either use static values, or variables within the component’s local scope. See the following examples:

在您的情况下,普通赋值有效,但对象赋值无效。将其更改为:

import React from 'react';
import { StaticImage } from 'gatsby-plugin-image';

const TestPage = (props) => {
  const testSrc = 'https://images.unsplash.com/photo-1523413651479-597eb2da0ad6?w=161&fit=crop';
  const testSrc2 = 'https://images.unsplash.com/photo-1563298723-dcfebaa392e3?w=161&fit=crop';

  return (
    <>
      <StaticImage src={testSrc} alt="Bed" />
      <StaticImage src={testSrc2} alt="Kitchen" />
    </>
  )
}

export default TestPage;