graphQL 查询中的字符串插值

Bab*_*boo 8 javascript typescript graphql gatsby

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

这是工作组件:

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} />}
  />
);
Run Code Online (Sandbox Code Playgroud)

这是我试图拥有可自定义图像的内容:

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} />}
  />
);
Run Code Online (Sandbox Code Playgroud)

但它会为查询引发以下错误:

Expected 1 arguments, but got 2.ts(2554)

如何拥有可自定义的图像名称?

ram*_*nok 4

这是我遇到的简单方法:

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 />
  }
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

<Image name="firstImg" />
Run Code Online (Sandbox Code Playgroud)

您还可以通过引入一个包含您可能想要显示的所有图像的对象来使其拼写安全,如下所示:

const Images = { firstImg: 'firstImg', secondImg: 'secondImg' }
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

<Image name={Images.firstImage} />
Run Code Online (Sandbox Code Playgroud)

...
switch (props.name) {
case Images.firstImage:
...
Run Code Online (Sandbox Code Playgroud)