组件中的React / Gatsby动态背景图像

问题描述 投票:1回答:1

我有一个React组件,它基本上可以处理相关内容,向用户显示网站内的下一个/上一页内容。

此组件需要导入背景图像,以便我可以将它们用作组件内部的内联样式。但是,要知道我要导入哪个背景图像,我必须查看定义如下的道具:

<LocationRelated 
  previousLocationName="Columbus, OH"
  previousLocationPath="columbus"
  nextLocationName="St. Pete Beach, FL"
  nextLocationPath="st-pete-beach"
/>

但是,据我所知,在进入React的render函数之前,没有办法查看组件的道具 - 因此无法进行动态导入。

这是我在执行此操作时的破坏尝试,使用导入内部的ES6模板文字:

import React from "react"
import pfbRelatedPrevBGImagePath from '`../../images/grid/PFB_${this.props.previousLocationPath}.jpg`'
import pfbRelatedNextBGImagePath from '`../../images/grid/PFB_${this.props.nextLocationPath}.jpg`'

class LocationRelated extends React.Component {

  render() {

    const pfbRelatedPrevBG = { 
      backgroundImage: `linear-gradient( to bottom, rgba(1,1,1,0.2), rgba(2,2,2,0.2) ), url(${ pfbRelatedPrevBGImagePath })` 
    }
    const pfbRelatedNextBG = { 
      backgroundImage: `linear-gradient( to bottom, rgba(1,1,1,0.2), rgba(2,2,2,0.2) ), url(${ pfbRelatedNextBGImagePath })` 
    }

    return (
      <div>
        <aside className="pfb-longform-container">
          <section className="pfb-related-content">
            <h3 className="pfb-related-content-title">Additional Locations</h3>
            <section className="pfb-related-image-container">
              <div 
                className="pfb-related-1" 
                style= { pfbRelatedPrevBG }
              >
                <p className="pfb-related-text">{ this.props.previousLocationName }</p>
              </div>
              <div 
                className="pfb-related-2"
                style= { pfbRelatedNextBG }
              >
                <p className="pfb-related-text">{ this.props.nextLocationName }</p>
              </div>
            </section>
          </section>
        </aside>
      </div>
    )
  }
}

export default LocationRelated

我的webpack构建器出错了,说基本上它不能读取this.props.whatever,因为它还没有定义,当它试图读取import时。有没有办法做到这一点?

附加说明:我正在为此站点使用Gatsby静态站点生成器,但这不应该真正影响正在发生的事情(至少我认为不应该)。

javascript reactjs background-image es6-modules gatsby
1个回答
3
投票

我认为上述方法是不可能的,但正如我发现的那样,这是不可能的。你必须完全放弃React(Gatsby)的做事方式,我上面的方法试图从Drupal / WordPress-CMS-build的角度来做这件事。

查看我修改的LocationRelated组件:

import React from "react"
import Link from 'gatsby-link'

class LocationRelated extends React.Component {

  render() {

    // Setup inline style objects using ES6 template literals which pull in the correct paths from the content pages themselves
    const pfbRelatedPrevBG = { 
      backgroundImage: `linear-gradient( to bottom, rgba(1,1,1,0.2), rgba(2,2,2,0.2) ), url(${ this.props.prevLocationImgPath.sizes.src })` 
    }
    const pfbRelatedNextBG = { 
      backgroundImage: `linear-gradient( to bottom, rgba(1,1,1,0.2), rgba(2,2,2,0.2) ), url(${ this.props.nextLocationImgPath.sizes.src })` 
    }

    return (
      <div className="pfb-related-bg-container">
        <aside className="pfb-related-container">
          <section className="pfb-related-content">
            <section className="pfb-related-image-container">
              <Link 
                to={ this.props.prevLocationPath }
                className="pfb-related-left-arrow"
              >
                <img src= { LeftArrow } alt="Navigate to the previous location in the PFB Annual Report" />
                <div className="pfb-related-left-arrow-text">Previous</div>
              </Link>
              <Link 
                to={ this.props.prevLocationPath }
                className="pfb-related-1" 
                style={ pfbRelatedPrevBG }
              >
                <p className="pfb-related-text">{ this.props.prevLocationName }</p>
              </Link>
              <Link 
                to={ this.props.nextLocationPath }
                className="pfb-related-2"
                style= { pfbRelatedNextBG }
              >
                <p className="pfb-related-text">{ this.props.nextLocationName }</p>
              </Link>
              <Link 
                to={ this.props.nextLocationPath }
                className="pfb-related-right-arrow"
              >
                <img src= { RightArrow } alt="Navigate to the next location in the PFB Annual Report" />
                <div className="pfb-related-right-arrow-text">Next</div>
              </Link>
            </section>
          </section>
        </aside>
      </div>
    )
  }
}

export default LocationRelated

您会注意到与上述尝试没有太大区别,但要注意this.props.nextLocationImgPath.sizes.src对象文字中使用的backgroundImage路径。你必须将backgroundImage作为道具传递给源路径。不要试图像我一样在组件中这样做。 React关注点的分离是关于从组件中获取数据,而是通过props提供数据。

那么问题就变成了:如果你必须将路径作为道具传递,那么当你在页面级别调用组件时,如何获得路径?

如果你正在使用Gatsby(你应该),你需要使用GraphQL来获得优化的图像路径。在我的例子中,我们将在我们称之为background-image组件的同一页面上调用LocationRelated路径。

我的页面的简化示例专注于手头的问题:

import React from 'react'
import Img from "gatsby-image";

import LocationRelated from '../components/LocationRelated'

class CharlotteLocation extends React.Component {
  render() {
    return (
      <div>    
        <LocationRelated 
          prevLocationName="Detroit"
          prevLocationPath="detroit"
          prevLocationImgPath= { this.props.data.charlottePrevImage }
          nextLocationName="Montana"
          nextLocationPath="montana"
          nextLocationImgPath= { this.props.data.charlotteNextImage }
        />
      </div>
    )
  }
}

export default CharlotteLocation 

// GraphQL queries for each image
export const CharlotteImageQuery = graphql`
  query CharlotteImageQuery {
    charlottePrevImage: imageSharp(id: { regex: "/PFB_DETROIT/" }) {
      sizes(maxWidth: 600 ) {
        ...GatsbyImageSharpSizes_withWebp
      }
    },
    charlotteNextImage: imageSharp(id: { regex: "/PFB_MONTANA/" }) {
      sizes(maxWidth: 600 ) {
        ...GatsbyImageSharpSizes_withWebp
      }
    }
  }
`

这些GraphQL查询提供了我们需要的文件的优化路径,现在我们可以通过LocationRelated将它们发送到我们的this.props.data组件中。

gatsby-image和GraphQL起初有点棘手,所以请查看this nice tutorial by Kyle Gill。它让我比Gatsby文档做得更好。

作为参考,这里是我如何在项目中设置我的gatsby-config.js以使所有这些插件很好地一起工作(我从我的项目而不是组件中的独立images目录中提取图像,所以我需要gatsby-source-filesystem来制作所有这项工作与gatsby-imagegatsby-transformer-sharpgatsby-plugin-sharp,):

module.exports = {
  siteMetadata: {
    title: 'PFB2017 Site',
  },
  //pathPrefix: "/pfb2017-site",
  plugins: [
    // Adds in React Helmet for metadata
    `gatsby-plugin-react-helmet`,

    // Gives us sass in the project
    `gatsby-plugin-sass`,

    // This plugin transforms JSON, which is how we are storing our location data
    `gatsby-transformer-json`,

    // Adds in Gatsby image handling
    `gatsby-image`,
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,

    /** 
     * This is how you customize gatsby-source-filesystem
     * Check this page out for more background 
     * https://www.gatsbyjs.org/docs/building-with-components 
     * By default, the gatsby-default starter kit comes with the `pages` directory wired up
     * I'm adding it here for consistency but you don't need it
     * What I have added into the starter are `images` and `data`, subfolders we'll need for the PFB project
     * 
     */

    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `pages`,
        path: `${__dirname}/src/pages`,
      },
    },    
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `data`,
        path: `${__dirname}/src/data`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`
      }
    }
  ],
};
© www.soinside.com 2019 - 2024. All rights reserved.