css - Gatsby 图像 : how to import the processed image into css and use it with background-image property

标签 css graphql gatsby

我成功地将 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 查询选择的那个.

关于css - Gatsby 图像 : how to import the processed image into css and use it with background-image property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52379126/

相关文章:

html - 圆覆盖不拉伸(stretch) 100%

reactjs - 如何将变量传递给 GraphQL 过滤器查询?

css - 背景图像似乎在 Sitefinity 4 中被过滤

css - 根据百分比更改 Bootstrap 进度条颜色

javascript - 卡在未定义的 "Cannot read property ' props' 处”

javascript - GraphQL 抛出语法错误

javascript - Apollo GraphQL,有没有办法在查询期间操纵正在写入缓存的数据?

javascript - 设置触发 reactjs-popup

reactjs - Gatsby:从内容字段创建页面

html - 无法更改文本输入颜色