And*_*sky 5 gatsby gatsby-image
我正在尝试显示包含图像 url 的对象数组中的几个图像。我知道 StaticImage 必须接受局部变量作为 props 值。图像 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;
Run Code Online (Sandbox Code Playgroud)
正如你所说,组件中有一个限制:
\n\n\n使用限制
\nStaticImage图像是在构建时加载和处理的,因此\n向组件传递道具的方式存在限制。这些值需要在构建时进行静态分析,这意味着您可以将它们作为组件外部的 props 传递,或者使用函数调用的结果等。您可以使用静态值,也可以使用组件\xe2\x80\x99s 本地范围内的变量。请参阅以下\n示例:
\n
在您的情况下,普通分配有效,但对象分配无效。将其更改为:
\nimport React from \'react\';\nimport { StaticImage } from \'gatsby-plugin-image\';\n\nconst TestPage = (props) => {\n const testSrc = \'https://images.unsplash.com/photo-1523413651479-597eb2da0ad6?w=161&fit=crop\';\n const testSrc2 = \'https://images.unsplash.com/photo-1563298723-dcfebaa392e3?w=161&fit=crop\';\n\n return (\n <>\n <StaticImage src={testSrc} alt="Bed" />\n <StaticImage src={testSrc2} alt="Kitchen" />\n </>\n )\n}\n\nexport default TestPage;\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
2004 次 |
| 最近记录: |