简体   繁体   English

ReactJS 取数据 html 数据处理

[英]ReactJS fetched html data manupilation

I have a mongodb database where I saved raw html in it.我有一个 mongodb 数据库,我在其中保存了原始 html。 I have created a custom attribute in the html called kk-id to mention objects inside the html.我在 html 中创建了一个名为 kk-id 的自定义属性,以提及 html 中的对象。 I want to replace that particular html tag with an anchor tag.我想用锚标签替换那个特定的 html 标签。

I figured a way to do it using vanilla javascript , however I was wondering if there was a more efficient reactjs way to do it.我想出了一种使用香草 javascript的方法,但是我想知道是否有更有效的reactjs方法来做到这一点。

data example数据示例

<p>Hello <span kk-id="123">John Doe</span></p>

where John Doe's id is 123 saved in it. John Doe 的 id 是123保存在其中。

/// react component
import React, { useEffect, useState } from "react";

export default function TestComponent() {
  const [html, setHtml] = useState(
    `<p>Hello <span kk-id="123">John Doe</span><br /></p>`
  );

  useEffect(() => {
    const span = document.querySelector(`[kk-id]`);
    if (span) {
      const a = document.createElement("a");
      a.href = "/people/john-doe";
      a.innerText = span.innerText;
      span.parentNode.replaceChild(a, span);
    }
  }, [html]);

  return <div dangerouslySetInnerHTML={{ __html: html }} />;
}

I hope vanilla js is the simplest way to do it.我希望 vanilla js 是最简单的方法。 For enhancement purpose you can see this .出于增强目的,您可以看到这个 it will be more readable and reusable.它将更具可读性和可重用性。

You can use html-react-parser and just do您可以使用html-react-parser并执行

import parse from "html-react-parser";
...

const newParsedHtml = parse(html, {
    replace: ({attribs}) => {
        if (domNode.attribs && domNode.attribs.id === "123") {
            return <span>dynamic text here</span>
        }
    }
});

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

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