Gatsby&GraphQL-文件下载链接

时间:2019-10-18 14:01:19

标签: download gatsby graphql-js

我正在用Gatsby构建一个静态网站,我需要在上面放置一些.txt或.pdf文件,以便访问者可以下载它们。我该怎么做?

我是新手,我的GraphQL知识真的很薄,我仅使用它来获取一些图像到组件中。我的“ gatsby-config.js”包含以下内容:

{
  resolve: `gatsby-source-filesystem`,
  options: {
    name: `documents`,
    path: `${__dirname}/src/documents`,
  },
},

我尝试了一些操作,在GraphiQL上,这似乎是有效的代码:

const data = useStaticQuery(graphql`
    query {
      document1: file(relativePath: {eq: "doc1.txt"}) {
        id
      }
    }
`) 

但是我不知道如何在JSX中下载该'document1'。

1 个答案:

答案 0 :(得分:2)

总是值得在GraphiQL explorer中查看可查询的内容。然后,您可以按照the default starter's image component.

中的静态查询示例进行操作

如果您正在使用Gatsby> v2.1,则可以使用useStaticQuery挂钩进行此操作。

import React from "react"
import { useStaticQuery, graphql } from "gatsby"

const Download = () => {
  const data = useStaticQuery(graphql`
    query MyQuery {
      file(relativePath: {eq: "doc1.txt"}) {
        publicURL
        name
      }
    }
  `)
  return <a href={data.file.publicURL} download>Download {data.file.name}</a>
}

export default Download

如果没有,您可以使用Static query

import React from "react"
import { StaticQuery, graphql } from "gatsby"

const Download = () => (
  <StaticQuery
    query={graphql`
      query MyQuery {
        file(relativePath: {eq: "doc1.txt"}) {
          publicURL
          name
        }
      }
    `}
    render={data => <a href={data.file.publicURL} download>Download {data.file.name}</a>}
  />
)

export default Download