@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>
);
}
下面可以检查您可以自定义的全部元素列表,以及每个元素可用的道具.
achildren: 反应节点;href: 字符串;className: 字符串;rel: 字符串;id: 字符串;title: 字符串;openInNewTab:布尔;
classchildren: 反应节点;className: 字符串;
imgsrc: 字符串;title: 字符串;width:号码;height:号码;mimeType: 图像MIMETYPES;altText: 字符串;
videosrc: 字符串;title: 字符串;width:号码;height:号码;
iframeurl: 字符串;width:号码;height:号码;
h1children: 反应节点;
h2children: 反应节点;
h3children: 反应节点;
h4children: 反应节点;
h5children: 反应节点;
h6children: 反应节点;
pchildren: 反应节点;
ulchildren: 反应节点;
olchildren: 反应节点;
lichildren: 反应节点;
tablechildren: 反应节点;
table_headchildren: 反应节点;
table_header_cellchildren: 反应节点;
table_bodychildren: 反应节点;
table_rowchildren: 反应节点;
table_cellchildren: 反应节点;
blockquotechildren: 反应节点;
boldchildren: 反应节点;
italicchildren: 反应节点;
underlinechildren: 反应节点;
codechildren: 反应节点;
code_blockchildren: 反应节点;
自定义资产
丰富的文本字段允许您嵌入资产 。 默认情况下,我们会将图像,视频和音频从盒子中取出. 然而,可以定义每个MIME类型组的自定义组件. 下面可以看到完整的列表 mimeType 组合.
audioapplicationimagevideofontmodeltext
我们没有组件来渲染字体,模型,文字和应用程序文件,但您可以根据您的需要和工程来自己写作. 如果需要,您也可以为特定设备安装自定义渲染器 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>;
},
},
}}
/>
);
}
实例
Next.js 链接组件
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;
Gatsby 链接组件
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制作 加入我们的社区来啊!