问题
I am making text editor using, react-draft-wysiwyg and draftjs-to-html ..
And also I have injected the dynamic html into editor like,
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)}
/>
</>
);
}
Current Working scenario:
Here the things are working very well and I am able to get the plain text like,
This text needs to display along with the html tags surrounded
inside the editor.
Note: (I mean to say only text is displayed without the html tags like div, span..
Expected:
I am in the need to bind the entire HTML as it is inside the editor like,
<div class="heading"> This text needs to display along with the <span> html tags </span> surrounded </div>
Working Snippet:
So my requirement is that need to display the text inside editor as,
<div class="heading"> This text needs to display along with the <span> html tags </span> surrounded </div>
instead of
This text needs to display along with the html tags surrounded
回答1:
As already stated by @Rod911 you can do something like this:
import "../carousel.css";
import React from "react";
import ContentEditor from "../components/text_editor";
function escape(unescaped) {
return unescaped
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function unescape(escaped) {
return escaped
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, '"')
.replace(/'/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)}
/>
</>
);
}
May be it would be nice to use a specific Class for the content, which would simplify the convertion. May be take a look at: https://www.itsrainingmani.dev/blog/string-prototype-extension/
回答2:
Try this:
export default function App() {
function getConvertedText(text) {
console.log(text);
text = text.replace(/</g, "<").replace(/>/g, ">");
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)
}
/> <
/>
);
}
来源:https://stackoverflow.com/questions/65699046/how-to-include-html-tags-in-text-editor-snippet-attached