graphQL 查询中的字符串插值 [英] String interpolation in graphQL query

查看:20
本文介绍了graphQL 查询中的字符串插值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Gatsby 及其用于检索资产的 graphQL 查询系统的新手.我有一个工作组件 Image 可以获取图像并显示它.我想自定义图像的名称,但我不知道如何修改.

I am new to Gatsby and its graphQL query system to retrieve assets. I have a working component Image that fetches an image and displays it. I want to have the name of the image customizable but I can't figure out how to dit.

这是工作组件:

const Image = () => (
  <StaticQuery
    query={graphql`
      query {
        // fetching the image gatsby-astronaut.png
        placeholderImage: file(relativePath: { eq: "gatsby-astronaut.png" }) {
          childImageSharp {
            fluid(maxWidth: 300) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    `}
    render={data => <Img fluid={data.placeholderImage.childImageSharp.fluid} />}
  />
);

这是我尝试过的可自定义图像:

And here is what I tried to have a customizable image:

const Image = ({ imgName }: { imgName: string }) => (
  <StaticQuery
    query={graphql`
      query {
        // fetching the image imgName
        placeholderImage: file(relativePath: { eq: "${imgName}.png" }) {
          childImageSharp {
            fluid(maxWidth: 300) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    `}
    render={data => <Img fluid={data.placeholderImage.childImageSharp.fluid} />}
  />
);

但它引发了以下查询错误:

But it raises the following error for the query:

需要 1 个参数,但得到 2.ts(2554)

如何获得可自定义的图像名称?

How can I have a customizable image name?

推荐答案

这是我遇到的简单方法:

Here is the easy way I ran into:

const Image = props => {
  const data = useStaticQuery(graphql`
    query {
      firstImg: file(relativePath: { eq: "firstImg.png" }) {
        childImageSharp {
          fluid(maxWidth: 300) {
            ...GatsbyImageSharpFluid
          }
        }
      }

      secondImg: file(
        relativePath: { eq: "secondImg.png" }
      ) {
        childImageSharp {
          fluid(maxWidth: 300) {
            ...GatsbyImageSharpFluid
          }
        }
      }
    }
  `)

  switch (props.name) {
    case "firstImg":
      return <Img fluid={data.firstImg.childImageSharp.fluid} />
    case "secondImg":
      return <Img fluid={data.secondImg.childImageSharp.fluid} />
    default:
      return <Img />
  }
}

并像这样使用它:

<Image name="firstImg" />

您还可以通过引入一个包含您可能想要显示的所有图像的对象来防止打字错误,如下所示:

You can also make it typo-safe by introducing an object with all the images you might want to display, like this:

const Images = { firstImg: 'firstImg', secondImg: 'secondImg' }

然后像这样使用它:

<Image name={Images.firstImage} />

...
switch (props.name) {
case Images.firstImage:
...

这篇关于graphQL 查询中的字符串插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆