简体   繁体   English

如何从 React 中的文本呈现特定的 HTML 标签?

[英]How to render specific HTML tags from a text in React?

I have a dynamic text coming from my server with some HTML tags in it.我有一个来自我的服务器的动态文本,其中包含一些 HTML 标记。 I don't want to "dangerouslySetInnerHTML" because of security reasons and because I only want to allow specific html tags like <i> <b> <strong> <em> .由于安全原因,我不想“dangerouslySetInnerHTML”,因为我只想允许特定的 html 标签,如<i> <b> <strong> <em> I don't want to allow any other tag to be rendered like for example or我不想让任何其他标签被渲染,例如或

So let's say I have the following string所以假设我有以下字符串

This is a text with a <b>bold</b> tag and a <strong>strong</strong> tag. It also includes <i>italic</i> and <em>em</em> tags.

If I render this text I want to render it as followed in my HTML:如果我呈现这个文本,我想在我的 HTML 中呈现它:

This is a text with a bold tag and a strong tag.这是一个带有粗体标签和标签的文本。 It also includes italic and em tags.它还包括斜体em标签。

I fixed this by using the dompurify library and created a reusable component in React.我通过使用dompurify库解决了这个问题,并在 React 中创建了一个可重用的组件。

html-tag-renderer.js html-tag-renderer.js

import React from 'react';
import DOMPurify from 'dompurify';
import PropTypes from 'prop-types';

const HTMLTagRenderer = ({ string, allowedTags }) => {
  const cleanHTML = DOMPurify.sanitize(string, { ALLOWED_TAGS: allowedTags });

  return <div dangerouslySetInnerHTML={{ __html: cleanHTML }} />;
};

HTMLTagRenderer.propTypes = {
  string: PropTypes.string.isRequired,
  allowedTags: PropTypes.array.isRequired,
};

export default HTMLTagRenderer;

can be used like:可以像这样使用:

 <HTMLTagRenderer allowedTags={['b', 'em', 'strong', 'i']} string="This is a text with a <b>bold</b> tag and a <strong>strong</strong> tag. It also includes <i>italic</i> and <em>em</em> tags." />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM