反应使用危险地使用SetInnerHTML渲染带有html标签的json [英] react use dangerouslySetInnerHTML to render json with html tags

查看:327
本文介绍了反应使用危险地使用SetInnerHTML渲染带有html标签的json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用列表中字符串中的html标签呈现json列表,如下所示 jsbin 。它在Jsbin中工作。但是在我的控制台中,我收到以下警告:

I am trying to render a json list with html tags in the string in a list as follows jsbin. It works in Jsbin. But in my console I got warning below:

warning  Only set one of `children` or `props.dangerouslySetInnerHTML` react/no-danger-with-children

只是想知道是否还有其他方法可以危险地呈现列表SetInnerHTML以避免

just wonder if there is other way to render the list with dangerouslySetInnerHTML to avoid the warning?

const displayList = [
    {
        item: 1,
        text: "<strong>ABC</strong> this should be strong."
    },
    {
        item: 2,
        text: "<a>ABC</a> this should be link."
    },
    {
        item: 3,
        text: "normal text"
    }
];

const App = () => (
    <ul>
        {displayList.map((item, i) => (
            <li key={i}>
                <div dangerouslySetInnerHTML={{
                    __html: item.text
                }}>
                </div>
            </li>
        ))}
    </ul>
);

ReactDOM.render(
    <App />,
    document.getElementById('root')
);


推荐答案

React抱怨使用 dangerouslySetInnerHTML 与安全的反应儿童结合在一起,发生在当您将div标签打开到具有这种特征的< div> open并为儿童准备好了< / div>

React is complaining about the use of dangerouslySetInnerHTML in conjunction with safe react children, that happened when you let the div tag opened to such characteristic <div>open and ready for children</div>.

由于使用的是JSX语法扩展,因此这里的解决方案是将整个句子写在一行中:

Since you are using the JSX syntax extension, the solution here is write the whole sentence in a single line:

<div dangerouslySetInnerHTML={{__html: item.text}}></div>

或仅使用单例div标签:

or just using a singleton div tag:

<div dangerouslySetInnerHTML={{
       __html: item.text
     }}/>

通过这种方式,您不会在jsbin上收到错误,因为它是一个反应生产版本,因此该版本并不意味着要告诉您什么可以写得更好。

By the way you are not getting the error on jsbin because it is a react production build, this build is not meant to tell you what could be written better.

这篇关于反应使用危险地使用SetInnerHTML渲染带有html标签的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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