如何解决如何在内容丰富的富文本中呈现超链接?
我有一个 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>
)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。