在下面的设置中没有可见的background-image。作为调试步骤,我尝试在const background中设置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>发布于 2019-03-03 14:22:17
因此,正如您在评论中发布的链接中所述,包含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( ... );
`} />查询它
PublicURL
如果您使用的是任何默认的启动程序,那么您的src/images文件夹很可能是用gatsby-source-file-system设置的,这样盖茨比就可以知道您的图像了。假设您知道该文件的名称,您可以这样查询它:
{
// ⇣ `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
}
}
`ImageSharp
盖茨比通常伴随着sharp,它允许你转换图像&更多。对于一个简单的示例,此查询将图像大小调整为200 to宽度:
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);
`} />如果在gatsby-config.js中使用withPrefix,则从gatsby导入withPrefix并将其包装在图像路径周围。
以下是前两个方法的码箱。
希望这能帮上忙!
https://stackoverflow.com/questions/54846377
复制相似问题