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

时间:2018-02-20 21:03:16

标签: javascript reactjs background-image es6-modules gatsby

我有一个基本上做相关内容的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静态网站生成器,但这不应该真正影响正在发生的事情(至少我认为不应该这样)。

1 个答案:

答案 0 :(得分: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的关注点分离是关于从组件中获取数据,而是通过道具提供数据。

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

如果您正在使用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`
      }
    }
  ],
};