簡體   English   中英

HTML-React-Parser 返回 object - 不是字符串?

[英]HTML-React-Parser returning object - not string?

我正在嘗試解析一些基本的 HTML - 例如:

<p style="color: black">Hi Guys!</p>

進入 JSX 代碼,我正在使用 HTML-React-Parser。 我已經將它鏈接到我的 HTML 中,如下所示:

<script src="https://unpkg.com/html-react-parser@latest/dist/html-react-parser.min.js">

我正在嘗試在這里使用它:

<script type="module">
  import bbCodeParser from "./node_modules/js-bbcode-parser/src/simple.js";
  const finishUpload = document.querySelector("#uploadFinish");
  const getTextButton = document.querySelector(".textUpload");

  function getURL() {
    var imageURL = document.querySelector(".headerInfo > div:nth-child(5)")
      .innerHTML;
    var imageURLParse = bbCodeParser.parse(imageURL);
    var myRegex = /<img[^>]+src="(https:\/\/[^">]+)"/g;
    var imageSRC = myRegex.exec(imageURLParse);
    console.log(imageSRC[1]);
  }

  getTextButton.addEventListener("click", function () {
    getText();
  });

  finishUpload.addEventListener("click", function () {
    getURL();
  });

  function getText() {
    var myContent = tinymce.activeEditor.getContent();
    var reactCode = HTMLReactParser('<p style="color: black">Hi Guys!</p>');
    console.log(reactCode);
  }
</script>
<script>
  const dateElement = document.querySelector("#date");
  var d = new Date();
  var months = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
  ];
  month = months[d.getMonth()];
  day = d.getDate();
  year = d.getFullYear();
  time = new Date().toLocaleTimeString([], {
    hour: "2-digit",
    minute: "2-digit",
  });

  dateElement.innerHTML = `Posted on ${month} ${day}, ${year} at ${time}`;
</script>

它工作正常,但問題是當我運行它時,它會返回一個 object,如下所示:

{…}
​
"$$typeof": Symbol(react.element)
​
_owner: null
​
_self: null
​
_source: null
​
_store: Object { … }
​
key: null
​
props: Object { style: {…}, children: "Hi Guys!" }
​
ref: null
​
type: "p"
​
<prototype>: Object { … }

而且我不確定該怎么做。 我真正需要的只是一個簡單的字符串。 任何幫助將不勝感激。 提前致謝。

HTMLReactParser將 HTML 字符串轉換為一個或多個 React 元素。 所以結果不會是你預期的字符串:

HTMLReactParser('<p style="color: black">Hi Guys!</p>');
// will be equal to React.createElement('p', { style: 'color: black' }, 'Hi Guys!')

可以在他們的文檔中查看一些示例:

<ul>
  {HTMLReactParser(`
    <li>Item 1</li>
    <li>Item 2</li>
  `)}
</ul>

參考: https://www.npmjs.com/package/html-react-parser

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM