【发布时间】:2021-05-21 18:30:34
【问题描述】:
我正在使用 React 和 Javascript,并且有一个要求,我需要提取某些锚标记,获取它们的属性,如 id、href 并从中创建一个自定义的 React 链接组件。
我的字符串看起来像这样
"<p>Bla bla bla bla.</p>\n<ul>\n<li><strong>Bla bla</strong>. Bla bla bla.</li>\n<li><strong>Bla bla bla</strong>.<a href='#footnote1' id='sup1'><sup>1</sup></a> Bla bla bla.</li>\n<li><strong>Bla bla bla.<a href='#footnote2' id='sup2'><sup>2</sup></a>\r\n</strong>&#160; Bla bla bla.</li>\n<li><strong>Bla bla:</strong>Bla bla <a href=\"https://google.com\" target=\"no\">Google</a> * bla bla bla.<a href='#footnote1' id='sup3'><sup>1</sup></a></li>\n</ul>\n<p>&#160;</p>"
我只想提取其中包含<sup> 的所有<a>。然后我想获取此类<a> 的属性并创建一个自定义的 React 链接组件,例如
<MyLink
id={id of the anchor tag}
addClasses={"footnote-link"}
href={href of anchor tag}
handleClick={myClickHandler}
ariaProps={{
label: {text inside the sup tag}
}}
>
<sup className={href of anchor tag !== null ? "custom-class" : ""}>{text inside the sup tag}</sup>
</MyLink>
然后我想用字符串中的自定义组件替换那些<a>。我试图将<a> 转换为自定义组件的原因是我希望新的锚标记符合 A11Y 并且锚标记和源字符串不在我的控制范围内。
我尝试了How to get the href value of an anchor tag with javascript from a string 和javascript regex to extract anchor text and URL from anchor tags 的组合,但没有取得太大进展。 我也试过react-string-replace,但也没多大帮助。
我还可以选择将<a href='#footnote1' id='sup1'><sup>1</sup></a> 替换为#FootNote({id:\"sup1-CB\", goto:\"sup1\", data:\"1\"})#FootNote 之类的东西,然后使用“id”、“goto”和“data”来创建自定义链接。
谁能提供一些关于如何实现这一目标的指导? 对于这个冗长的问题,我深表歉意。
【问题讨论】:
-
我最终使用了这个解决方案stackoverflow.com/a/38969310/6586554,它最终使用了html-to-react 自定义库github.com/mikenikles/html-to-react。
标签: javascript reactjs