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

查看:105
本文介绍了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:

Expected 1 arguments, but got 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天全站免登陆