首页 > 解决方案 > 如何在文本编辑器中包含 html 标签?[附上片段]

问题描述

我正在使用react-draft- wysiwyg和draftjs-to-html制作文本编辑器。

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

index.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

标签: javascriptreactjstext-editordraftjsreact-draft-wysiwyg

解决方案


尝试这个:

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)
        }
        /> <
        />
    );
}

推荐阅读