【问题标题】:Component props to GraphQLGraphQL 的组件道具
【发布时间】:2018-07-08 07:44:29
【问题描述】:

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

所以,我创建了一个 Image 组件来接收其道具的路径:

<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
          }
        }
      }
    }
`;

这样做的正确方法是什么?

【问题讨论】:

  • 你可以选择最适合 gats-by 框架的contentful cms,如果你想要内容丰富我有解决方案?

标签: javascript reactjs graphql gatsby netlify-cms


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    虽然我不能你的 GraphQL 类型或你的阿波罗?设置(我建议运行查询以测试您如何使用 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 
    

    【讨论】:

      猜你喜欢
      • 2017-09-03
      • 1970-01-01
      • 2020-02-11
      • 2021-02-23
      • 2021-11-10
      • 1970-01-01
      • 2017-11-27
      • 2020-09-12
      • 2021-09-02
      相关资源
      最近更新 更多