请问,有什么方法可以正确解析包含 html 标签和条带内一些文本的内容< and >。
我已经尝试过:
import DOMPurify from 'dompurify';
import parse from 'html-react-parser';
const htmlString = '<p>test<br/><img src="....." />... <[email protected]></p>';
const cleanedHTML = DOMPurify.sanitize(htmlString);
<td>{parse(cleanedHTML)}</td>
使用此方法会导致我出现错误:未捕获的 DOMException:字符串包含无效字符。
尝试使用辅助库;
dompurify
和html-react-parser
这是如何使用这些库的示例:
import React from 'react';
import DOMPurify from 'dompurify';
import parse from 'html-react-parser';
const MyComponent = () => {
const htmlString = '<p>test<br/><img src="....." />... <[email protected]></p>';
// Sanitize the HTML string to remove potentially unsafe elements and attributes
const cleanedHTML = DOMPurify.sanitize(htmlString);
const customParse = (html) => {
const strippedTags = ['emailtouser'];
return parse(html, {
replace: (domNode) => {
if (domNode.type === 'tag' && strippedTags.includes(domNode.name)) {
return null; // Remove the specified tags
}
},
});
};
return <td>{customParse(cleanedHTML)}</td>;
};
export default MyComponent;