GraphQL 的组件道具

Component props to GraphQL

我正在使用 ReactGatsbyJS 构建一个简单的 Web 应用程序,我使用 NetlifyCMS 来管理内容。使用 gatsby-transformer-remark 我加载包含我想使用 gatsby-transformer-sharp.

加载的图像路径的数据

所以,我创建了一个 Image 组件,它接收其 props 的路径:

<Image path={post.frontmatter.thumbnail} />

我想让这个组件获取路径,用 GraphQL 请求一个 gatsby-transformer-sharp 节点,然后在 gatsby-img 组件中使用返回的数据。

我对 React 和 GatsbyJS 都很陌生,所以显然我的解决方案不起作用。

import React from 'react';
import Img from 'gatsby-image';

export default class Image extends React.Component {
  render() {
    return(
      <Img
        sizes={this.props.file.childImageSharp.sizes}
      />
    );
  }
}

export const getSizesQuery = graphql`
  query GatsbyImageSampleQuery($path: this.props.path) {
      file(relativePath: { eq: $path }) {
        childImageSharp {
          sizes {
            base64
            tracedSVG
            aspectRatio
            src
            srcSet
            srcWebp
            srcSetWebp
            sizes
            originalImg
            originalName
          }
        }
      }
    }
`;

正确的做法是什么?

虽然我看不懂你的 GraphQL 类型或你的 apollo??设置(我建议 运行 查询来测试你如何使用 graphiql 或 Apollo 客户端开发工具或类似的东西获取你的数据,首先你会看到你的数据是如何从 graphql 解析的),但你的代码应该是这样的。 .

import React from 'react';
import Img from 'gatsby-image';
import { gql, graphql } from 'react-apollo'; //Apollo client

class Image extends React.Component {
  render() {
    return(
      <Img 
       // get access to the graphql data with this.props.data
        sizes={this.props.data.file.childImageSharp.sizes} 

      />
    );
  }
}

   const getSizesQuery = gql`
    query GatsbyImageSampleQuery($path: ID!) {
      file(relativePath: $path) {
        childImageSharp {
          sizes {
            base64
            tracedSVG
            aspectRatio
            src
            srcSet
            srcWebp
            srcSetWebp
            sizes
            originalImg
            originalName
          }
        }
      }
    }
`;

const ImageWithData =  graphql(getSizesQuery , {
  name : 'selectCustomer',
  options: (ownProps) => ({
    variables: {
      path: ownProps.path // set your path like this
    }
  })
})(Image);

export default ImageWithData 

Gatsby 将您的所有数据拉入其内部节点系统,然后通过布局或页面中的查询将数据推送到您的组件。

这种单一的入口源确保 Gatsby 可以将您的所有数据编译为静态 JSON。 @toufek-khoury 提供的方法会将数据传递给您的组件,但它会绕过 Gatsby 缓存。在几乎所有情况下,您都希望缓存数据,这就是 Gatsby 如此快得令人难以置信的原因。

解决方案是获取 pageQuery 中页面所需的所有数据。