以下设置看不到background-image
。作为调试步骤,我尝试在background: pink
中设置const background
,此操作确实有效,确认emotion
运行正常。
打开React Dev Tools extension
时,我看到background-image: url(../images/page_backgroundgradient.png), url(../images/page_background.png);
的应用没有错误。
请问我的问题是什么?
我的文件结构如下:
frontend/
src/
images/
page_background.png
page_backgroundgradient.png
pages/
index.js
我要向其中添加背景图片的index.js
。
...
import { css, Global } from "@emotion/core"
const background = css`
background-image: url(../images/page_backgroundgradient.png), url(../images/page_background.png);
`
<div css={background}>
...
</div>
答案 0 :(得分:5)
因此,如您在评论中发布的链接中所述,有多种方法可以在gatsby中包含图像/资产:
graphql
import
图片,获取路径static
目录假设您有一个像这样的组件:
// src/pages/sample.js
import React from 'react'
import { css } from '@emotion/core'
export default () => <div css={css`
width: 10rem;
height: 10rem;
background: url( ... );
`} />
如果您使用任何默认启动器,则您的src/images
文件夹可能已设置为gatsby-source-file-system
,因此Gatsby知道您的图像。假设您知道文件名,则可以像这样查询它:
{
// ⇣ `base` is file name with extension.
file (base: { eq: "image.png" }) {
publicURL
}
}
如链接中所述,查询字段publicURL
将为您提供文件名的路径:
export default ({ data }) => <div css={css`
width: 10rem;
height: 10rem;
background: url(${data.file ? data.file.publicURL : 'your/fallback.png'});
`} />
export const query = graphql`
query {
file(base: { eq: "image.png" }) {
publicURL
}
}
`
盖茨比通常带有sharp
,可让您变换图像及更多。举一个简单的例子,此查询将图像的大小调整为200px宽度:
export const query = graphql`
query {
file(base: { eq: "image.png" }) {
childImageSharp {
fixed(width: 200) {
src
}
}
}
}
`
您可以在data.file.childImageSharp.fixed.src
上访问它。
让webpack处理它:
import myImagePath from '../relative/path/to/image.png';
export default () => <div css={css`
width: 10rem;
height: 10rem;
background: url(${myImagePath});
`} />
static
目录在根文件夹中创建一个名为static
的目录,除非已经存在一个目录。将您的图片复制到其中:
root
|--src
`--static
`--image.png
所有静态文件都将直接复制以构建,因此您可以像这样链接到图像:
export default () => <div css={css`
width: 10rem;
height: 10rem;
background: url(/image.png);
`} />
如果您在pathPrefix
中使用gatsby-config.js
,请从withPrefix
导入gatsby
并将其包裹在图像路径周围。
前两种方法是codesandbox。
希望有帮助!