我正在从事一个 Gatsby 项目,但遇到了一个令人沮丧的问题。我有一个组件接收图像的相对路径作为 props,然后我用它来填充 background-image
属性:
import React, { FC } from 'react'
// Prop typings
type TProps = {
imageUrl: string;
}
const MyComponent: FC<TProps> = ({ imageUrl }) => {
const divStyles = {
backgroundImage: `url(${imageUrl})`,
}
return (
<div style={divStyles}></div>
)
}
export default MyComponent
imageUrl
中传递的相对路径引用了我的 src
目录中的图像。我已经仔细检查了路径是否正确并且图像存在,但是在组件渲染时图像不会出现。
我可以使用 CSS 成功设置背景图像,但是当图像路径作为 prop 传递时它会失败。我还尝试使用 Gatsby 的 withPrefix
实用程序函数设置图像 URL,但没有骰子。
我做错了什么,还是无法从 props 在 Gatsby 中定义背景图像?
回答1
如果您想显示这样的图像,这不是 Gatsby
问题,而是与 React
相关的问题。
这是在 React
中导入图像并使用 props
传递的正确方法:
// Parent component
import image from "../relative/path/to/image";
<MyGreatComponent image={image} />
// MyGreatComponent
export default function MyGreatComponent({ image }) {
const divStyles = {
backgroundImage: `url(${image}`,
}
return (
<div style={divStyles}></div>
)
}
参考:https://create-react-app.dev/docs/adding-images-fonts-and-files/
快乐黑客!
回答2
是我做错了什么,还是无法在 props 的 Gatsby 中定义背景图像?
您应该能够像任何其他 React 项目一样。
我认为您可能面临的唯一问题是路径的相对性。在不知道当前的违规路径 (imageUrl
) 或您的项目结构的情况下,很难猜测,但请尝试以下操作:
import React, { FC } from 'react'
// Prop typings
type TProps = {
imageUrl: string;
}
const MyComponent: FC<TProps> = ({ imageUrl }) => {
const divStyles = {
backgroundImage: `url(../${imageUrl})`,
}
return (
<div style={divStyles}></div>
)
}
export default MyComponent