如何在文本编辑器中包含 html 标签?[附上片段]

IT技术 javascript reactjs text-editor draftjs react-draft-wysiwyg
2021-05-06 19:51:19

我正在使用react-draft- wysiwygdraftjs-to-html制作文本编辑器..

而且我已经将动态 html 注入到编辑器中,例如,

索引.js:

export default function App() {
  const dynamicData = `<div class="heading"> This text needs to display along with the <span> html tags </span> surrounded </div>`;

  const handleInputChange = (e) => {
    console.log("event ", e.target.value);
  };

  return (
    <>
      <ContentEditor
        name="dynamicContent"
        value={dynamicData}
        onChange={(event) => handleInputChange(event)}
      />
    </>
  );
}

当前工作场景:

在这里,一切运行良好,我能够得到纯文本,例如,

This text needs to display along with the html tags surrounded

在编辑器里面。

注意:(我的意思是说只显示文本而不显示 div、span 等 html 标签。

预期的:

我需要绑定整个 HTML,就像它在编辑器中一样,

<div class="heading"> This text needs to display along with the <span> html tags </span> surrounded </div>

工作片段:

编辑 next.js + css-only carousel (forked)

所以我的要求是需要将编辑器中的文本显示为,

<div class="heading"> This text needs to display along with the <span> html tags </span> surrounded </div>

替代

This text needs to display along with the html tags surrounded

2个回答

正如@Rod911 已经说过的那样,您可以执行以下操作:

import "../carousel.css";
import React from "react";
import ContentEditor from "../components/text_editor";

function escape(unescaped) {
  return unescaped
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}

function unescape(escaped) {
  return escaped
    .replace(/&amp;/g, "&")
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&quot;/g, '"')
    .replace(/&#039;/g, "'");
}

export default function App() {
  const dynamicData = escape(
    `<div class="heading">This text needs to display along with the <span> html tags </span> surrounded </div>`
  );

  const handleInputChange = (e) => {
    console.log("event ", unescape(e.target.value));
  };

  return (
    <>
      <ContentEditor
        name="dynamicContent"
        value={dynamicData}
        onChange={(event) => handleInputChange(event)}
      />
    </>
  );
}

为内容使用特定的类可能会很好,这将简化转换。可以看看:https : //www.itsrainingmani.dev/blog/string-prototype-extension/

试试这个:

export default function App() {

    function getConvertedText(text) {
        console.log(text);
        text = text.replace(/</g, "&lt;").replace(/>/g, "&gt;");
        return text;
    }
    const dynamicData = '<div class="heading"> This text needs to display along with the ' + getConvertedText("<span> html tags </span>") + ' surrounded </div>';

    const handleInputChange = (e) => {
        console.log("event ", e.target.value);
    };

    return ( <
        >
        <
        ContentEditor name = "dynamicContent"
        value = {
            dynamicData
        }
        onChange = {
            (event) => handleInputChange(event)
        }
        /> <
        />
    );
}