【问题标题】:Gatsby & GraphQL - render a download link from a queried fileGatsby & GraphQL - 从查询文件中呈现下载链接
【发布时间】:2020-02-15 13:04:53
【问题描述】:

我正在使用 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”。

【问题讨论】:

    标签: reactjs gatsby graphql-js


    【解决方案1】:

    总是值得在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
    

    【讨论】:

    • 这正是我所需要的。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2020-03-23
    • 2021-02-03
    • 2021-07-03
    • 2020-11-15
    • 2019-06-12
    • 2020-08-17
    • 2019-05-18
    • 2020-11-14
    相关资源
    最近更新 更多