【发布时间】:2020-04-16 14:38:54
【问题描述】:
我有一个文件夹content/projects,其中包含以下方式的文件:
project-a.de.mdproject-a.en.mdproject-b.de.mdproject-b.en.md
现在我如何构建一个组件来显示其中的一些项目,这些项目在其frontmatter 中有featured 标志并且是特定语言的?
我创建了以下组件:
import React from 'react'
import { FormattedMessage } from 'react-intl'
import { useStaticQuery, graphql } from 'gatsby'
import Content from '../Content'
import { FeaturedProjectsQuery } from '../../../graphql-types'
const FeaturedProjects: React.FC = () => {
const projects = useStaticQuery<FeaturedProjectsQuery>(graphql`
query FeaturedProjects {
allMarkdownRemark(filter: { fileAbsolutePath: { regex: "/(content/projects)/" }, frontmatter: { featured: { eq: true } } }) {
nodes {
frontmatter {
title
}
}
}
}
`)
return (
<Content>
<h2>
<FormattedMessage id="navigation.projects" />
</h2>
{projects.allMarkdownRemark.nodes.map(p => {
return <div>{p.frontmatter?.title}</div>
})}
</Content>
)
}
export default FeaturedProjects
这可行,但我必须在 TypeScript 中过滤当前语言(我通过 React 上下文),尽管我认为这是 GraphQL 查询的完美任务,因为它是为选择事物而设计的。
很遗憾,我不能在静态查询中使用变量。您将如何实现这一目标?
Tl;博士
我尝试使用变量创建查询,但 graphql 标记中不允许使用字符串插值。
...
allMarkdownRemark(filter: { fileAbsolutePath: {
regex: `/(content/projects).*\\.${lang}\\.md$/` ...
}
...
【问题讨论】:
标签: reactjs typescript graphql gatsby