react use dangerouslySetInnerHTML to render json with html tags

前端 未结 3 1102
醉话见心
醉话见心 2021-01-19 03:16

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          


        
相关标签:
3条回答
  • 2021-01-19 03:43

    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 }}
    />
    
    0 讨论(0)
  • 2021-01-19 03:46

    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.

    0 讨论(0)
  • 2021-01-19 03:52

    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.

    0 讨论(0)
提交回复
热议问题