首页 > 解决方案 > 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%;
}

标签: cssgraphqlgatsby

解决方案


我为此使用了 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 查询选择的图像。


推荐阅读