Fro*_*maz 2 reactjs graphql-js gatsby
我正在用 Gatsby 构建一个静态网站,我需要在上面放一些 .txt 或 .pdf 文件,以便访问者可以下载它们。我该怎么做?
我是新手,我的 GraphQL 知识真的很薄,我只用它来为我的组件获取一些图像。我的“gatsby-config.js”包含以下内容:
{
resolve: `gatsby-source-filesystem`,
options: {
name: `documents`,
path: `${__dirname}/src/documents`,
},
},
Run Code Online (Sandbox Code Playgroud)
我尝试了一些东西,在 GraphiQL 上这似乎是有效的代码:
const data = useStaticQuery(graphql`
query {
document1: file(relativePath: {eq: "doc1.txt"}) {
id
}
}
`)
Run Code Online (Sandbox Code Playgroud)
但我不知道如何在 JSX 中下载“document1”。
在GraphiQL 资源管理器中查看可查询的内容总是值得的。然后你可以按照默认启动器的图像组件中的静态查询示例。
如果你使用 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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1036 次 |
| 最近记录: |