我正在尝试解析一些基本的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>
它工作得很好,但问题是当我运行它时,它会返回一个像这样的对象:
{…}
"$$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