简体   繁体   English

如果 html 标签来自 React Component 中的数组,如何将它们呈现为 html 标签而不是字符串?

[英]How to render html tags as html tags instead of string if they are coming from an array in React Component?

For example, I have an array of 3 values in it.例如,我有一个包含 3 个值的数组。 The values also have some html tags.这些值也有一些 html 标签。 When I try to map through that array and try to display each of my array item, the values are displayed as it is.当我尝试通过该数组访问 map 并尝试显示我的每个数组项时,值按原样显示。 I want the HTML tags in my array values to be executed as true html elements.我希望我的数组值中的 HTML 标记作为真正的 html 元素执行。 Below is my App.js code of my sample react app:下面是我的示例反应应用程序的 App.js 代码:

 const App = () => { const [questions, setQuestions] = useState([ "<h1>Test 1</h1>", "<h1>Test 2</h1>", "<h1>Test 3</h1>", ]); return ( <div> {questions.map((question) => ( <div>{question}</div> ))} </div> ); }; export default App;

The above react component give me my output as following:上面的反应组件给我 output 如下:

<h1>Test 1</h1>
<h1>Test 2</h1>
<h1>Test 3</h1>

However, I want my final output to be look like below in which the html h1 tags are applied on my array elements when displayed in the browser.但是,我希望我的最终 output 如下所示,其中 html h1 标签在浏览器中显示时应用于我的数组元素。 I know if I write such sort of html tags in a vanilla javascript, the html page renders it correctly by automatically reading any html tags as true html tags but I dont know how to achieve it in React Component.我知道如果我在香草 javascript 中编写此类 html 标签,html 页面会通过自动读取任何 html 标签作为真正的 html 标签来正确呈现它,但我不知道如何在 React Component 中实现它。

Test 1测试 1

Test 2测试 2

Test 3测试 3

You can use dangerouslySetInnerHTML(question) inside your map function instead of the <div>{question}</div> inside the render to get the desired behavior, but please be cautious while using it.您可以在 map function 中使用dangerouslySetInnerHTML(question)而不是渲染中的<div>{question}</div>以获得所需的行为,但在使用时请谨慎。 It can lead to unwanted security risk (hence the name) like XSS.它可能会导致不必要的安全风险(因此得名),例如 XSS。

More information: https://reactjs.org/docs/dom-elements.html更多信息: https://reactjs.org/docs/dom-elements.html

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

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