react use dangerouslySetInnerHTML to render json with html tags

做~自己de王妃 提交于 2020-08-19 15:29:08

问题


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

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')
);

回答1:


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>.

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>

or just using a singleton div tag:

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

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.




回答2:


Remove the enclosing tag of your div element in your component so that it looks like the following code:

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

According to this, it should remove the warning.




回答3:


Add inline comment on top of dangerouslySetInnerHTML and inside div element if you use ESLint

<div
   // eslint-disable-next-line react/no-danger
   dangerouslySetInnerHTML={{ __html: html }}
/>


来源:https://stackoverflow.com/questions/43795680/react-use-dangerouslysetinnerhtml-to-render-json-with-html-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!