Gatsby-将StaticQuery的结果传递给子级

时间:2018-10-09 21:12:36

标签: gatsby

在我的版式中,根据v2启动程序,我正在使用StaticQuery从我的配置中获取标题。我也想将其提供给children-具体来说,是用于显示博客文章的模板。

我该怎么做?

布局:

import React from "react";
import Helmet from "react-helmet";
import { StaticQuery, graphql } from "gatsby";
import Header from "./Header";

const Layout = ({ children }) => (
  <StaticQuery
    query={graphql`
      query SiteTitleQuery {
        site {
          siteMetadata {
            title
            description
          }
        }
      }
    `}
    render={data => {
      const { title } = data.site.siteMetadata;
      return (
        <>
          <Helmet
            title={title}
          >
            <html lang="en" />
          </Helmet>
          <Header siteTitle={title} />
          <main>{children}</main>
        </>
      );
    }}
  />
);

export default Layout;

帖子模板:

import React from "react";
import Helmet from "react-helmet";
import { graphql } from "gatsby";
import Layout from "./Layout";

const Post = ({ title, data }) => {
  const { markdownRemark: post } = data;
  return (
    <Layout>
      <div className="blog-post-container">
        <Helmet title={`${title} - ${post.frontmatter.title}`} />
        <div className="blog-post">
          <h1>{post.frontmatter.title}</h1>
          <div
            className="blog-post-content"
            dangerouslySetInnerHTML={{ __html: post.html }}
          />
        </div>
      </div>
    </Layout>
  );
};

export const pageQuery = graphql`
  query BlogPostByPath($path: String!) {
    markdownRemark(frontmatter: { path: { eq: $path } }) {
      html
      frontmatter {
        date(formatString: "MMMM DD, YYYY")
        path
        title
      }
    }
  }
`;

export default Post;

来自this GitHub问题:

const childrenWithProps = React.Children.map(children, (child) =>
  React.cloneElement(child, { title })
);

return <div>{childrenWithProps}</div>;

但是,当尝试在我的Post模板中使用props.title时,却无法定义。

0 个答案:

没有答案