不通过点符号接受 Gatsby StaticImage src 值
Gatsby StaticImage src value not accepted via dot notation
我知道您不能将图像源作为函数的结果传递给 StaticImage 组件。但是,谁能给我解释一下这两个例子的区别。
import React from 'react'
import { StaticImage } from 'gatsby-plugin-image' // to take image data and render it
export default function Example() {
const imageSrc = '../images/jonathan-adams.jpg'
const data = {
imageSrc: '../images/jonathan-adams.jpg',
}
return (
<div>
<StaticImage src={imageSrc} alt="alt text" /> {/* works */}
<StaticImage src={data.imageSrc} alt="alt text" /> {/* doesn't work */}
</div>
)
}
一个是直接变量引用,后者是引用相同的值,但通过点符号。点符号是函数吗?
Is dot notation a function?
它不是一个函数,但它不是一个常量值(至少在 StaticImage
组件的范围内它不能被视为常量)因此它不能被静态分析,因为在最后,它的常量是 data
,而不是它的嵌套属性。这就是 imageSrc
有效而 data
无效的原因。
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.
也就是说,您可能想要使用 imageSrc
方法或考虑使用接受动态值的 GatsbyImage
(它将需要重构和基于 GraphQL 的方法)。
我知道您不能将图像源作为函数的结果传递给 StaticImage 组件。但是,谁能给我解释一下这两个例子的区别。
import React from 'react'
import { StaticImage } from 'gatsby-plugin-image' // to take image data and render it
export default function Example() {
const imageSrc = '../images/jonathan-adams.jpg'
const data = {
imageSrc: '../images/jonathan-adams.jpg',
}
return (
<div>
<StaticImage src={imageSrc} alt="alt text" /> {/* works */}
<StaticImage src={data.imageSrc} alt="alt text" /> {/* doesn't work */}
</div>
)
}
一个是直接变量引用,后者是引用相同的值,但通过点符号。点符号是函数吗?
Is dot notation a function?
它不是一个函数,但它不是一个常量值(至少在 StaticImage
组件的范围内它不能被视为常量)因此它不能被静态分析,因为在最后,它的常量是 data
,而不是它的嵌套属性。这就是 imageSrc
有效而 data
无效的原因。
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.
也就是说,您可能想要使用 imageSrc
方法或考虑使用接受动态值的 GatsbyImage
(它将需要重构和基于 GraphQL 的方法)。