微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Gatsby 的 StaticImage 中使用动态外部网址

如何解决在 Gatsby 的 StaticImage 中使用动态外部网址

我正在尝试从包含图像 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

使用 StaticImage

的限制

图像在构建时加载和处理,所以有 将 props 传递给组件的方式的限制。价值观需要 在构建时进行静态分析,这意味着您无法通过 它们作为组件外部的道具,或使用结果 函数调用,例如。您可以使用静态值,或者 组件局部范围内的变量。请参阅以下内容 示例:

在您的情况下,普通分配有效,但对象分配无效。改为:

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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。