【问题标题】:How do I pass a className to a image component in Gatsby如何将 className 传递给 Gatsby 中的图像组件
【发布时间】:2019-07-25 06:27:16
【问题描述】:

我正在使用 gatsby-image 和 gatsby-source-filesytem 我希望 img 标签(徽标组件)在呈现为 html 时具有 classNamelogo 我该怎么做呢,gatsby-image 文档说通过道具传递。我还是不太明白react,所以需要帮助理解这里是我的代码。

logo.js

import React from "react"
import { StaticQuery, graphql } from "gatsby"
import Img from "gatsby-image"

/*
 * This component is built using `gatsby-image` to automatically serve optimized
 * images with lazy loading and reduced file sizes. The image is loaded using a
 * `StaticQuery`, which allows us to load the image from directly within this
 * component, rather than having to pass the image data down from pages.
 *
 * For more information, see the docs:
 * - `gatsby-image`: https://gatsby.app/gatsby-image
 * - `StaticQuery`: https://gatsby.app/staticquery
 */

const Image = () => (
  <StaticQuery
    query={graphql`
      query {
        placeholderImage: file(relativePath: { eq: "riel-type.png" }) {
          childImageSharp {
            fluid(maxWidth: 300) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    `}
    render={data => <Img fluid={data.placeholderImage.childImageSharp.fluid} />}
  />
)
export default Image

index.js

import React from "react"
import { Link } from "gatsby"

import Layout from "../components/layout"
import Image from "../components/image"
import Logo from "../components/logo"
import SEO from "../components/seo"

const IndexPage = () => (
  <Layout>
    <SEO title="Home" keywords={[`gatsby`, `application`, `react`]} />
    <div className="row">
      <div className="col-4">
        <Logo />
      </div>
    </div>
  </Layout>
)

export default IndexPage

【问题讨论】:

    标签: reactjs gatsby react-props


    【解决方案1】:

    gatsby-image 文档说要通过 props 传递它

    意味着您可以在Img 标记内添加您想要的任何属性。由于某些内部限制,您必须使用 JavaScript 名称属性而不是 HTML 属性(即 className 而不是 class

    所以:

    render={data => <Img fluid={data.placeholderImage.childImageSharp.fluid} className="logo" />}
    

    【讨论】:

      猜你喜欢
      • 2020-10-30
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      相关资源
      最近更新 更多