简体   繁体   English

html-react-parser:用另一个包含内部文本子节点(A-link)的 DOM 节点替换 DOM 节点

[英]html-react-parser: Replace DOM Node with another DOM Node containing inner text child (A-link)

Using html-react-parser , I need to output my string as JSX, but with the replacement of all <a href=... > to the encapsulating new element <LinkContainer to={href}><a>..</a></LinkContainer> which will contain the <a> .使用html-react-parser ,我需要将我的字符串输出为 JSX,但是将所有<a href=... > 替换为封装的新元素<LinkContainer to={href}><a>..</a></LinkContainer> <a href=... <LinkContainer to={href}><a>..</a></LinkContainer>将包含<a> In other words, I'm wrapping my A-links in a LinkContainer tag.换句话说,我将我的 A-links 包装在 LinkContainer 标签中。

The problem is, I don't know how to express the Inner Text of the A-tag I'm replacing, which has to be included:问题是,我不知道如何表达我要替换的 A 标签的内部文本,必须包括:

parse(successMessage, { 
        replace: domNode => {
            if (domNode.attribs && domNode.attribs.href) {
                return <LinkContainer to={domNode.attribs.href}><a href="#">How to get the Inner Text?</a></LinkContainer>;
            }  
        }}
    );

Nothing like innerText or text is available.没有像innerTexttext这样的东西可用。 The DOM Nodes that come to me are来找我的 DOM 节点是

  • The A-tag itself A标签本身
  • Its child, which is inner text, a separate node它的子节点,即内部文本,一个单独的节点

I found the solution.我找到了解决方案。 You can just replace the A-tag and get the link's text from domNode.children[0].data .您可以只替换 A-tag 并从domNode.children[0].data获取链接的文本。

    parse(successMessage, { 
            replace: domNode => {
                if (domNode.attribs && domNode.attribs.href) {
                    return <LinkContainer to={domNode.attribs.href}><a href="#">{domNode.children[0].data}</a></LinkContainer>;
                }  
            }}
        )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM