@graphcms/rich-text-react-renderer

中文文档
0.6.2发布于 2024/08/16MITTypeScriptESM + CJS近 30 天下载 2.9万

Hygraph 丰富的文本反应渲染器

中文使用文档
文档目录20 节
  1. 开始
  2. 使用/实例
  3. 自定义元素
  4. 自定义资产
  5. 参考资料
  6. 自定义嵌入
  7. 参考资料
  8. 链接嵌入
  9. 空元素
  10. 类型脚本
  11. 儿童类型
  12. 自定义嵌入/嵌入
  13. 实例
  14. Next.js 链接组件
  15. Next.js 图像组件
  16. Next.js 图像组件的占位符图像
  17. Gatsby 链接组件
  18. Gatsby 图像组件
  19. 代码块 棱镜.js
  20. 许可证

@graphcms/rich-text-react-resterser (英语)

React应用程序中的Render Rich Text内容.

开始

你可以在npm或Yarn得到它.

# npm
npm i @graphcms/rich-text-react-renderer

# Yarn
yarn add @graphcms/rich-text-react-renderer

使用/实例

为了在您的应用程序上显示内容, 您需要提供从 Hygraph API 返回到 RichText 组件。 内容必须返回 raw (或 json作为AST代表的形式。 欲了解如何查询丰富文本内容的更多信息, 检查我们的文件。 。 。 .

import { RichText } from '@graphcms/rich-text-react-renderer';

const content = {
  children: [
    {
      type: 'paragraph',
      children: [
        {
          bold: true,
          text: 'Hello World!',
        },
      ],
    },
  ],
};

function App() {
  return <RichText content={content} />;
}

上述例子的内容将:

<p>
  <b>Hello world!</b>
</p>

自定义元素

默认情况下,元素将没有任何造型,尽管 IFrame,我们设计的反应。 但是,如果你有,比如说,一个设计系统,并且想要使用自己的组件,带有外形,你可以通过一个 renderers 给 RichText 组件。 举个例子:

import { RichText } from '@graphcms/rich-text-react-renderer';

const content = {
  /* ... */
};

function App() {
  return (
    <div>
      <RichText
        content={content}
        renderers={{
          h1: ({ children }) => <h1 className="text-white">{children}</h1>,
          bold: ({ children }) => <strong>{children}</strong>,
        }}
      />
    </div>
  );
}

下面可以检查您可以自定义的全部元素列表,以及每个元素可用的道具.

  • a
    • children: 反应节点;
    • href: 字符串;
    • className: 字符串;
    • rel: 字符串;
    • id: 字符串;
    • title: 字符串;
    • openInNewTab:布尔;
  • class
    • children: 反应节点;
    • className: 字符串;
  • img
    • src: 字符串;
    • title: 字符串;
    • width:号码;
    • height:号码;
    • mimeType: 图像MIMETYPES;
    • altText: 字符串;
  • video
    • src: 字符串;
    • title: 字符串;
    • width:号码;
    • height:号码;
  • iframe
    • url: 字符串;
    • width:号码;
    • height:号码;
  • h1
    • children: 反应节点;
  • h2
    • children: 反应节点;
  • h3
    • children: 反应节点;
  • h4
    • children: 反应节点;
  • h5
    • children: 反应节点;
  • h6
    • children: 反应节点;
  • p
    • children: 反应节点;
  • ul
    • children: 反应节点;
  • ol
    • children: 反应节点;
  • li
    • children: 反应节点;
  • table
    • children: 反应节点;
  • table_head
    • children: 反应节点;
  • table_header_cell
    • children: 反应节点;
  • table_body
    • children: 反应节点;
  • table_row
    • children: 反应节点;
  • table_cell
    • children: 反应节点;
  • blockquote
    • children: 反应节点;
  • bold
    • children: 反应节点;
  • italic
    • children: 反应节点;
  • underline
    • children: 反应节点;
  • code
    • children: 反应节点;
  • code_block
    • children: 反应节点;

自定义资产

丰富的文本字段允许您嵌入资产 。 默认情况下,我们会将图像,视频和音频从盒子中取出. 然而,可以定义每个MIME类型组的自定义组件. 下面可以看到完整的列表 mimeType 组合.

  • audio
  • application
  • image
  • video
  • font
  • model
  • text

我们没有组件来渲染字体,模型,文字和应用程序文件,但您可以根据您的需要和工程来自己写作. 如果需要,您也可以为特定设备安装自定义渲染器 mimeType。这里有一个例子:

import { RichText } from '@graphcms/rich-text-react-renderer';

const content = [
  {
    type: 'embed',
    nodeId: 'cknjbzowggjo90b91kjisy03a',
    children: [
      {
        text: '',
      },
    ],
    nodeType: 'Asset',
  },
  {
    type: 'embed',
    nodeId: 'ckrus0f14ao760b32mz2dwvgx',
    children: [
      {
        text: '',
      },
    ],
    nodeType: 'Asset',
  },
];

const references = [
  {
    id: 'cknjbzowggjo90b91kjisy03a',
    url: 'https://media.graphassets.com/dsQtt0ARqO28baaXbVy9',
    mimeType: 'image/png',
  },
  {
    id: 'ckrus0f14ao760b32mz2dwvgx',
    url: 'https://media.graphassets.com/7M0lXLdCQfeIDXnT2SVS',
    mimeType: 'video/mp4',
  },
];

function App() {
  return (
    <RichText
      content={content}
      references={references}
      renderers={{
        Asset: {
          video: () => <div>custom VIDEO</div>,
          image: () => <div>custom IMAGE</div>,
          'video/mp4': () => {
            return <div>custom video/mp4 renderer</div>;
          },
        },
      }}
    />
  );
}

如前所述,你可以为所有人写出渲染器 mimeType 群体或特定群体 mimeType。 。 。 .

参考资料

需要查阅 RichText 用于提供嵌入式资产的组件.

id, (中文(简体) ), mimeType 财务报告和审定财务报表 url 需要输入 Asset 查询.

查询示例 :

{
  articles {
    content {
      json
      references {
        ... on Asset {
          id
          url
          mimeType
        }
      }
    }
  }
}

自定义嵌入

想象你有一个嵌入 Post 您的丰富文本字段。 为了制作它,你可以有一个定制的渲染器。 举个例子:

import { RichText } from '@graphcms/rich-text-react-renderer';

const content = [
  {
    type: 'embed',
    nodeId: 'custom_post_id',
    children: [
      {
        text: '',
      },
    ],
    nodeType: 'Post',
  },
];

const references = [
  {
    id: 'custom_post_id',
    title: 'Hygraph is awesome :rocket:',
  },
];

function App() {
  return (
    <RichText
      content={content}
      references={references}
      renderers={{
        embed: {
          Post: ({ title, nodeId }) => {
            return (
              <div className="post">
                <h3>{title}</h3>
                <p>{nodeId}</p>
              </div>
            );
          },
        },
      }}
    />
  );
}

参考资料

需要查阅 RichText 组件。 您还需要在询问中包含您的模型 .

  • id 在您的模型查询中总是需要。 如果它不在场,它不会使.
{
  articles {
    content {
      json
      references {
        ... on Asset {
          id
          url
          mimeType
        }
        # Your post query
        ... on Post {
          id # required
          title
          slug
          description
        }
      }
    }
  }
}

富文字场也支持Link Embeds,它的工作类似于普通的嵌入. 根据型号名称,可以为其设置自定义渲染器. 示例

import { RichText } from '@graphcms/rich-text-react-renderer';

const content = [
  {
    type: 'link',
    nodeId: 'post_id',
    children: [
      {
        text: 'click here',
      },
    ],
    nodeType: 'Post',
  },
];

const references = [
  {
    id: 'post_id',
    slug: 'hygraph-is-awesome',
  },
];

function App() {
  return (
    <RichText
      content={content}
      references={references}
      renderers={{
        link: {
          Post: ({ slug, children }) => {
            return <a href={`/blog/${slug}`}>{children}</a>;
          },
        },
      }}
    />
  );
}

空元素

默认情况下,我们从元素列表中删除了空标题来防止SEO问题. 其他要素,例如: thead 也可以删除。 您可以找到完整的列表 这里。 。 。 .

类型脚本

如果您在项目中使用了 TypeScript, 我们建议安装 @graphcms/rich-text-types 软件包。 它包含了元素的类型,与它们所接受的道具并列. 您可以在应用程序中使用它们来创建自定义组件 .

儿童类型

如果您需要从 Rich Text 字段输入内容,可以通过使用类型包来输入. 示例

import { ElementNode } from '@graphcms/rich-text-types';

type Content = {
  content: {
    raw: {
      children: ElementNode[];
    };
  };
};

自定义嵌入/嵌入

视参考查询和模型而定,字段可能会有变化,这适用于类型。 为了让DX更好的使用软件包,我们有 EmbedProps 财务报告和审定财务报表 LinkEmbedProps 可以导入的类型 @graphcms/rich-text-types (如果你还没有完成的话,你可能需要安装它).

在这个例子中,我们已经看到如何为一个 Post 模型,但它对任何其他模型和 Asset 在你的项目.

import { EmbedProps, LinkEmbedProps } from '@graphcms/rich-text-types';

type Post = {
  title: string;
  slug: string;
  description: string;
};

function App() {
  return (
    <RichText
      // ...
      renderers={{
        embed: {
          Post: ({ title, description, slug }: EmbedProps<Post>) => {
            return (
              <div className="post">
                <a href={`/blog/${slug}`}>
                  <h3>{title}</h3>
                  <p>{description}</p>
                </a>
              </div>
            );
          },
        },
        link: {
          Post: ({ slug, children }: LinkEmbedProps<Post>) => {
            return <a href={`/blog/${slug}`}>{children}</a>;
          },
        },
      }}
    />
  );
}

实例

import Link from 'next/link';
import { RichText } from '@graphcms/rich-text-react-renderer';

const content = {
  /* ... */
};

function App() {
  return (
    <RichText
      content={content}
      renderers={{
        a: ({ children, openInNewTab, href, rel, ...rest }) => {
          if (href.match(/^https?:\/\/|^\/\//i)) {
            return (
              <a
                href={href}
                target={openInNewTab ? '_blank' : '_self'}
                rel={rel || 'noopener noreferrer'}
                {...rest}
              >
                {children}
              </a>
            );
          }

          return (
            <Link href={href}>
              <a {...rest}>{children}</a>
            </Link>
          );
        },
      }}
    />
  );
}

Next.js 图像组件

import Image from 'next/image';
import { RichText } from '@graphcms/rich-text-react-renderer';

const content = {
  /* ... */
};

function App() {
  return (
    <RichText
      content={content}
      renderers={{
        img: ({ src, altText, height, width }) => (
          <Image
            src={src}
            alt={altText}
            height={height}
            width={width}
            objectFit="cover"
          />
        ),
      }}
    />
  );
}

由于图像在 Hygraph CDN 中, 您需要指定我们的域名 next.config.js 文档。 详情请检查 本指南。 。 。 .

module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: '**.graphassets.com',
      },
    ],
  },
};

Next.js 图像组件的占位符图像

对于低质量图像占位符( LQIP) 我们可以使用 标点符。平板符将生成我们传递给的已编码的基数64图像 next/image 作为 blurDataUrl 道具 (英语). 在这个例子中,我们将查询一个丰富的文本字段,并生成每个嵌入式资产的占位符图像.

首先,安装等离子符 :

# npm
npm i plaiceholder

# Yarn
yarn add plaiceholder

注意 : sharp 盖下,但是 next/image 我们不需要单独安装.

以下是一个完整被吹嘘的例子,一个有丰富文本内容的博客邮页.

// [slug.jsx]
import { RichText } from '@graphcms/rich-text-react-renderer';
import { getPlaiceholder } from 'plaiceholder';
import { fetchFromHygraph } from '../../lib/hygraph';
import Image from 'next/image';

// Page template
const SinglePostPage = ({ data }) => {
  const { title, description, content } = data;

  return (
    <>
      {/* ... */}
      <RichText
        content={content.json}
        references={content.references}
        renderers={{
          Asset: {
            image: ({ url, alt, caption, width, height, blurDataUrl }) => {
              return (
                <Image
                  src={url}
                  alt={alt}
                  width={width}
                  height={height}
                  placeholder={blurDataUrl ? 'blur' : 'empty'}
                  blurDataURL={blurDataUrl}
                />
              );
            },
          },
        }}
      />
    </>
  );
};

export const getStaticPaths = async () => {
  // Get your paths here.
};

export const getStaticProps = async context => {
  const data = await fetchFromHygraph({
    // Sample query, adjust to your content structure.
    // Note: 'id' and 'mimeType' are required for custom components.
    query: `
      query ($slug: String!) {
        post(where: { slug: $slug }) {
          slug
          content {
            json
            references {
              ... on Asset {
                id
                mimeType
                url
                alt
                caption
                width
                height
              }
            }
          }
        }
      }
    `,
    variables: {
      slug: context.params?.slug,
    },
    preview: context.preview,
  });

  // Pick images from assets
  const images = data.post.content.references.filter(asset =>
    asset.mimeType.includes('image')
  );

  // Use Plaiceholder to generate placeholder images (LQIP)
  // As a result the images will have a `blurDataUrl` prop with the
  // base64 encoded image.
  await Promise.all(
    images.map(async image => {
      const { base64 } = await getPlaiceholder(image.url);
      image.blurDataUrl = base64;
    })
  );

  return {
    props: {
      data: data.post,
    },
  };
};

export default SinglePostPage;
import { Link } from 'gatsby';
import { RichText } from '@graphcms/rich-text-react-renderer';

const content = {
  /* ... */
};

function App() {
  return (
    <RichText
      content={content}
      renderers={{
        a: ({ children, openInNewTab, href, rel, ...rest }) => {
          if (href.match(/^https?:\/\/|^\/\//i)) {
            return (
              <a
                href={href}
                target={openInNewTab ? '_blank' : '_self'}
                rel={rel || 'noopener noreferrer'}
                {...rest}
              >
                {children}
              </a>
            );
          }

          return (
            <Link to={href} {...rest}>
              {children}
            </Link>
          );
        },
      }}
    />
  );
}

Gatsby 图像组件

不幸的是,目前无法使用Gatsby图像组件与这个包. 这个 GatsbyImage 组件(用于动态图像)在构建时间内从查询中获取图像,而此时无法完成。 更多信息见 语法/丰富文本#16。 。 。 .

代码块 棱镜.js

默认情况下,你可能已经意识到, 由软件包提供的代码块 没有任何独特的造型,因为我们没有意见 它应该如何看待你的应用程序。 但是,如果需要的话,你可以创建您的代码块,为它添加一个背景颜色,添加一些粘贴,并根据需要进行调整.

如果你想走一步,你也可以与 棱镜.js 或者说 突出显示.js。下面您可以看到使用 Prism.js 的示例:

注:我们仍然不支持为富文本字段中的代码块定义自定义语言.

import { useEffect } from 'react';
import { RichText } from '@graphcms/rich-text-react-renderer';

import Prism from 'prismjs';
import 'prismjs/plugins/line-numbers/prism-line-numbers';
import 'prismjs/themes/prism-tomorrow.css';
import 'prismjs/plugins/line-numbers/prism-line-numbers.css';

const content = {
  /* ... */
};

function App() {
  useEffect(() => {
    Prism.highlightAll();
  }, []);

  return (
    <RichText
      content={content}
      renderers={{
        code_block: ({ children }) => {
          return (
            <pre className="line-numbers language-none">
              <code>{children}</code>
            </pre>
          );
        },
      }}
    />
  );
}

许可证

根据麻省理工学院的许可.


由Hygraph制作 加入我们的社区来啊!

版本与发布记录

@graphcms/rich-text-react-renderer 共发布 21 个版本,首次发布于 2021/05/12;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.6.2latest2024/08/162 年前
0.6.12022/07/044 年前
0.6.02022/07/024 年前
0.5.02022/04/064 年前
0.4.32022/03/224 年前
0.4.22022/01/134 年前

其他发布通道:canary → 0.1.1-canary.1。

关于 @graphcms/rich-text-react-renderer 的常见问题

@graphcms/rich-text-react-renderer 是什么?

Hygraph 丰富的文本反应渲染器

如何安装 @graphcms/rich-text-react-renderer?

在项目目录运行 npm install @graphcms/rich-text-react-renderer,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=16)、react-dom(>=16)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@graphcms/rich-text-react-renderer 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@graphcms/rich-text-react-renderer 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@graphcms/rich-text-react-renderer 可以商用吗?

@graphcms/rich-text-react-renderer 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@graphcms/rich-text-react-renderer 的下载量有多少?

根据 npm 官方下载统计,@graphcms/rich-text-react-renderer 在 2026/10/17 – 2026/11/15 这 30 天内被下载 28,808 次,日均约 960 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@graphcms/rich-text-react-renderer 还在维护吗?

最新版本 0.6.2 发布于 2024/08/16(2 年前);至今共发布 21 个版本,其中过去 12 个月发布了 0 个;首次发布于 2021/05/12。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。