reactjs - 如何在内容丰富的富文本中呈现超链接?
问题描述
我有一个 gatsby 应用程序,我在其中呈现富文本内容。一切都运行良好,除了我无法获取我在内容丰富的 CMS 中超链接的文本。当前代码如下所示,我可以获取 url 或 uri(在内容丰富的情况下),但不能获取我超链接的值/文本。任何人都可以帮忙吗?
import React from 'react';
import { graphql, Link } from 'gatsby';
import Img from 'gatsby-image';
import { renderRichText } from 'gatsby-source-contentful/rich-text';
import { BLOCKS, MARKS, INLINES } from '@contentful/rich-text-types';
const Bold = ({ children }) => <span className="bold">{children}</span>;
const Text = ({ children }) => <p className="align-center">{children}</p>;
const website_url = 'https://stackoverflow.com';
// Setting the rendering options. Same as:
// https://github.com/contentful/rich-text/tree/master/packages/rich-text-react-renderer
const options = {
renderMark: {
[MARKS.BOLD]: (text) => <Bold>{text}</Bold>
},
renderNode: {
[INLINES.HYPERLINK]: ({ data }) => (
<a
href={data.uri}
target={`${data.uri.startsWith(website_url) ? '_self' : '_blank'}`}
rel={`${data.uri.startsWith(website_url) ? '' : 'noopener noreferrer'}`}
>
{/* {node.content[0].value} */}
{console.log(data)}
</a>
),
[BLOCKS.PARAGRAPH]: (node, children) => <Text>{children}</Text>,
[BLOCKS.EMBEDDED_ASSET]: (node) => <Img fluid={node.data.target.fluid} />
}
};
function privacy({ data }) {
// console.log(data);
const description = data.allContentfulBlogPost.nodes[0].bodyRichText;
return <div>{description && renderRichText(description, options)}</div>;
}
export default privacy;
export const pageQuery = graphql`
query MyQuery {
allContentfulBlogPost {
nodes {
bodyRichText {
raw
references {
... on ContentfulAsset {
contentful_id
__typename
fluid {
...GatsbyContentfulFluid
}
}
}
}
}
}
}
`;
解决方案
内容丰富的 DevRel 在这里。
我想你要找的是children
. 它类似于您呈现段落的方式。
[INLINES.HYPERLINK]: ({ data }, children) => (
<a
href={data.uri}
target={`${data.uri.startsWith(website_url) ? '_self' : '_blank'}`}
rel={`${data.uri.startsWith(website_url) ? '' : 'noopener noreferrer'}`}
>{children}</a>
)
推荐阅读
- dart - F/flutter (10109): [FATAL:flutter/shell/common/switches.cc(133)] 检查失败:映射 && 大小。无法解析符号:_binary_icudtl_dat
- firebase - Firestore 基本问题:如何避免 N+1 加入请求
- azure - Azure ARM 模板部署 concat 构建 CosmosDB 连接字符串
- java - 将实体保存在集合中并嵌入到其他对象中
- csv - 平面文件目标列数据类型验证
- sql - JSON/CLOB Group by 运行时间长
- c# - Global.asax.cs 中的 Session_End 未触发
- pandas - AttributeError:“DataFrame”对象没有属性“DataFrame”
- javascript - 更改 JavaScript 中的文本突出显示颜色
- javascript - 交叉点观察者 rootBound 给出的值不正确