React - 如何在道具中传递 HTML 标签? [英] React - How to pass HTML tags in props?

查看:23
本文介绍了React - 如何在道具中传递 HTML 标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够传递带有 HTML 标签的文本,如下所示:

但是在 MyComponent 的渲染方法中,当我打印出 this.props.text 时,它实际上打印了所有内容:

这是<strong>不是</strong>在职的.

有什么方法可以让 React 解析 HTML 并正确地将其转储出来?

解决方案

您可以使用带有字符串和 JSX 元素的混合数组(请参阅文档 这里):

这里有一个小提琴显示它的工作原理:http://jsfiddle.net/7s7dee6L/>

此外,作为最后的手段,您始终拥有能力插入原始 HTML,但要小心,因为如果不清理属性值,这可能会使您面临跨站点脚本 (XSS) 攻击.

I want to be able to pass text with HTML tags, like so:

<MyComponent text="This is <strong>not</strong> working." />

But inside of MyComponent's render method, when I print out this.props.text, it literally prints out everything:

This is <strong>not</strong> working.

Is there some way to make React parse HTML and dump it out properly?

解决方案

You can use mixed arrays with strings and JSX elements (see the docs here):

<MyComponent text={["This is ", <strong>not</strong>,  "working."]} />

There's a fiddle here that shows it working: http://jsfiddle.net/7s7dee6L/

Also, as a last resort, you always have the ability to insert raw HTML but be careful because that can open you up to a cross-site scripting (XSS) attack if aren't sanitizing the property values.

这篇关于React - 如何在道具中传递 HTML 标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆