Gatsby 和 GraphQL - 从查询的文件中呈现下载 link

Gatsby & GraphQL - render a download link from a queried file

我正在用 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
      }
    }
`) 

但我不知道如何使 'document1' 可以在 JSX 中下载。

GraphiQL explorer to see what is available to query. Then you can just follow the example of the static query in 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