How to get Gatsby Images based on results of PageQuery?

女生的网名这么多〃 提交于 2020-02-04 04:19:06

问题


I'd like to do something like the following so I can get Gatsby Images dynamically:

const image = 'gastby-astronaut.png';

export const imageQuery = graphql`
  { allImageSharp (
    filter: {
      fluid: {
        originalName: {
          regex: "/${image}/"
        }
      }
    }
  ){
  edges { 
    node {
      fluid {
        originalName
      }
    }
  }
}
}
`;

However, I can't figure out how to connect this query to an initial query that would get the 'gatsby-astronaut.png', or perform this query from a subcomponent with a . I get this error when I try this:

Error: BabelPluginRemoveGraphQL: String interpolations are not allowed 
in graphql fragments. Included fragments should be referenced as
 `...MyModule_foo`.

Any suggestions on the proper way to return Gatsby Images dynamically?


回答1:


Ah, yeah Gatsby extracts GraphQL queries from your pages through static analysis: they load the file as text, parse it, and extract the query, all before the actual file gets executed. This means that your typical tagged-template literal functionality isn't there.

The only way to filter is through context provided when createPage is called from gatsby-node.js. I.e. if you do this:

exports.createPages = ({ graphql, actions }) =>
  graphql(`some query here`).then(result => {
    actions.createPage({
      path: "/output-path/",
      component: path.resolve(`./src/templates/your_template.jsx`),
      context: { image: result.data.yourImage },
    })
  })

Then you can do this in your page query:

query SomePage($image: String!) {
  allImageSharp (
    filter: {
      fluid: {
        originalName: {
          regex: $image
        }
      }
    }
  ){
    edges { 
      node {
        fluid {
          originalName
        }
      }
    }
  }
}



回答2:


Here's a solution I came up with... pretty janky, but it works:

import PropTypes from 'prop-types';
import React from 'react';
import Img from 'gatsby-image';
import { useStaticQuery, graphql } from 'gatsby';


const Image = ({ imageYouWant }) => {
  const data = useStaticQuery(
    graphql`
      query allTheImagesQuery{
        allImageSharp {
          edges {
            node {
              fluid(maxWidth:1000) {
                ...GatsbyImageSharpFluid
                originalName
              }
            }
          }
        }
      }`,
  );

  const TheImageYouWant = data.allImageSharp.edges
    .filter(edge => edge.node.fluid.originalName === imageYouWant)
    .map(myImage => <Img fluid={myImage.node.fluid} />);

  return (
    <>
      { TheImageYouWant }
    </>
  );
};


Image.propTypes = {
  imageYouWant: PropTypes.string,
};

Image.defaultProps = {
  imageYouWant: '',
};

export default Image;



来源:https://stackoverflow.com/questions/55131052/how-to-get-gatsby-images-based-on-results-of-pagequery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!