在 React 中,我需要获取 JavaScript String
并将其显示为 HTML。我正在使用 dangerouslySetInnerHTML
来完成此操作,但我想通过仅允许特定标签(例如 ul
和 li
)来更安全地完成此操作。我怎样才能做到这一点?
在下面的代码中,我只想允许 ul
和 li
标记。
<p
dangerouslySetInnerHTML={{
__html: '<ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul>'
}}></p>
当我尝试使用 sanitizeHtml
时,我得到以下信息:
./node_modules/sanitize-html/node_modules/postcss/lib/lazy-result.js
Module parse failed: Unexpected token (143:21)
You may need an appropriate loader to handle this file type.
最佳答案
有一个名为 sanitize-html 的开源库这正是你想要的。从他们的例子来看:
// Allow only a super restricted set of tags and attributes
const clean = sanitizeHtml(dirty, {
allowedTags: [ 'b', 'i', 'em', 'strong', 'a' ],
allowedAttributes: {
'a': [ 'href' ]
},
allowedIframeHostnames: ['www.youtube.com']
});
关于javascript - ReactangerlySetInnerHTML 仅允许特定的 HTML 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66779699/