首页 > 解决方案 > 如何在内容丰富的富文本中呈现超链接?

问题描述

我有一个 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
                            }
                        }
                    }
                }
            }
        }
    }
`;

标签: reactjscontentful

解决方案


内容丰富的 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>
)

推荐阅读