【问题标题】:How to query for a image in a rich-text field in Contentful如何在 Contentful 的富文本字段中查询图像
【发布时间】:2019-09-26 19:14:58
【问题描述】:

我正在通过使用 Contentful 作为 CRM 构建博客来学习 Gatsby,我不知道如何将它与 gatsby-images 一起使用以将图像显示到富文本字段的正文中,一直在搜索互联网并且仍然没有找到一个很好的例子来说明如何做到这一点。

我的 post.jsx:

import React from 'react';
import { graphql } from 'gatsby';
import { documentToReactComponents } from '@contentful/rich-text-react-renderer';

import Layout from '../components/layout';
import Image from '../components/image';

const renderBody = documentToReactComponents;

export const query = graphql`
  query($slug: String) {
    contentfulBlogPost(slug: { eq: $slug }) {
      title
      author
      date(formatString: "DD-MM-YYYY")
      /** body is my rich-text field*/
      body {
        json
      }
    }
  }`;

const Post = ({ data }) => {
  const {
    title,
    author,
    date,
    body: { json },
  } = data.contentfulBlogPost;

  const options = {
    renderNode: {
      'embedded-asset-block': (node) => {
        console.log(`Node: ${JSON.stringify(node, undefined, 2)}`);
        /** It works with no problems when using a simple img html tag */
        const src = node.data.target.fields.file['en-US'].url;
        const imageAlt = node.data.target.fields.file['en-US'].title;
        return (
          <Image alt={imageAlt} fluid={???}/>
        );
      },
    },
  };

  return (
    <Layout>
      <article>
        <h1>{title}</h1>
        <p>Author: {author}</p>
        <p>Date: {date}</p>
        { renderBody(json, options) }
      </article>
    </Layout>
  );
};

export default Post;

我已经使用 GraphiQL 至少一整天了,但仍然不知道在哪里以及如何使用 GatsbyContentfulFluid 以及插件页面中描述的富文本字段。

【问题讨论】:

  • 带着同样的问题来到这里。你想清楚了吗?

标签: gatsby contentful


【解决方案1】:

我在Gatsby-config.js 中使用downloadLocal: true 对图像问题进行了排序:

{
    resolve: `gatsby-source-contentful`,
    options: {
            spaceId: process.env.CONTENTFUL_SPACE_ID,
            // Learn about environment variables: https://gatsby.dev/env-vars
            accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
            downloadLocal: true,
        },
    },

这导致 Gatsby 在 body { json } 返回的 JSON 中公开了一堆额外的属性,这些属性以前没有被获取。

我(还)没有使用流体,但是这个线程上的人是:

https://github.com/contentful/rich-text/issues/70

【讨论】:

    猜你喜欢
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 2022-09-02
    相关资源
    最近更新 更多