使用 Fragment 插入通过 DangerouslySetInnerHTML 呈现在后端的 HTML [英] Using Fragment to insert HTML rendered on the back end via dangerouslySetInnerHTML

查看:65
本文介绍了使用 Fragment 插入通过 DangerouslySetInnerHTML 呈现在后端的 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经通过

<div key={ ID } dangerouslySetInnerHTML={ { __html: HTML } } />

将我的 HTML 包装成一个 <div>:

which wrapped my HTML into a <div>:

<div>my html from the HTML object</div>

现在 react > 16.2.0 已经支持对于 Fragments,我想知道我是否可以使用它来避免每次从后端获取数据时将 HTML 包装在 <div> 中.

Now react > 16.2.0 has support for Fragments and I wonder if I can use that somehow to avoid wrapping my HTML in a <div> each time I get data from the back end.

运行

<Fragment key={ ID } dangerouslySetInnerHTML={ { __html: HTML } } />

会发出警告

Warning: Invalid prop `dangerouslySetInnerHTML` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.
in React.Fragment

这还支持吗?还有其他方法可以解决这个问题吗?

Is this supported yet at all? Is there another way to solve this?

为它创建一个问题在反应仓库,如果你想给它点赞.

Created an issue in the react repo for it if you want to upvote it.

推荐答案

简短回答

不可能:

key 是唯一可以传递给 Fragment 的属性.在里面未来,我们可能会添加对其他属性的支持,例如事件处理程序.

key is the only attribute that can be passed to Fragment. In the future, we may add support for additional attributes, such as event handlers.

https://reactjs.org/docs/fragments.html

您可能想加入并建议将其作为未来的补充.

You may want to chime in and suggest this as a future addition.

https://github.com/facebook/react/issues

您可能需要考虑使用 HTML 解析库,例如:

You may want to consider using an HTML parsing library like:

https://github.com/remarkablemark/html-react-parser

查看此示例以了解它将如何实现您的目标:

Check out this example to see how it will accomplish your goal:

http://remarkablemark.org/blog/2016/10/07/dangerously-set-innerhtml-alternative/

您将能够做到这一点:

<>
{require('html-react-parser')(
    '<em>foo</em>'
)}
</>

这篇关于使用 Fragment 插入通过 DangerouslySetInnerHTML 呈现在后端的 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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