css - gatsby-image:如何将处理后的图像导入 css 并与 background-image 属性一起使用
问题描述
我成功地将 gatsby-image 实现到我的项目中,并替换了我的组件中使用的许多 img 标签。但现在我试图优化我的一些组件的背景图像,但我不知道如何使用 gatsby-image 会生成一个新的 img 标签,我不能用它来设置样式作为 div 元素的背景。s1 可以告诉我如何将生成的图像与 css 一起使用。这是我的代码:
const HeaderlineSection = ({headerOne}) => {
return(
<div className="header-back" ></div>
)
}
export const query = graphql`
query IndexPageQuery {
headerOne: imageSharp(id: { regex: "/header_one.jpg/" }) {
sizes(maxWidth: 1200 ) {
...GatsbyImageSharpSizes
}
}
}
以前,在我的 css 中,我使用未优化的图像作为背景图像:
.header-back {
background: url(../images/header_one.jpg) 50% 0 no-repeat;
height: 470px;
width: 100%;
}
解决方案
我为此使用了 gatsby-background-image插件。这是您如何使用它的一个示例:
import React from 'react'
import { graphql, StaticQuery } from 'gatsby'
import styled from 'styled-components'
import BackgroundImage from 'gatsby-background-image'
const BackgroundSection = ({ className }) => (
<StaticQuery query={graphql`
query {
desktop: file(relativePath: { eq: "seamless-bg-desktop.jpg" }) {
childImageSharp {
fluid(quality: 100, maxWidth: 4160) {
...GatsbyImageSharpFluid_withWebp
}
}
}
}
`}
render={data => {
const imageData = data.desktop.childImageSharp.fluid
return (
<BackgroundImage Tag="section"
className={className}
fluid={imageData}
backgroundColor={`#040e18`}
>
<h1>Hello gatsby-background-image</h1>
</BackgroundImage>
)
}
}
/>
)
const StyledBackgroundSection = styled(BackgroundSection)`
width: 100%;
background-repeat: repeat-y;
`
export default StyledBackgroundSection
代码是不言自明的,但基本上,元素将替换为您在Tag
属性中选择的元素,并将背景图像设置为使用 graphql imageSharp 查询选择的图像。
推荐阅读
- javascript - 关闭页面前的 JQuery ajax 清理代码
- java - 如何构建 Java `Map
` 出 ` 列表 >`? - python - 使用 __file__ 时出现 Python 错误 [WinError 123](文件名、目录名或卷标语法不正确)
- firebase - 无法从 Firebase 控制台下载 google-services.json
- python - 使用递归时,列表不会添加任何新元素
- opengl - glMapBuffer 在 Mac 上返回 NULL,在 Windows 上工作得很好
- c++ - 我以后可以将我的 Visual C++ win32 项目转换为跨平台吗?
- java - Android:如何使用卡片视图而不是按钮
- php - Laravel 5.5 - 读取存储在外部文件夹中的图像
- java - Spring Security @PreAuthorize 基于自定义布尔属性值