简体   繁体   English

如何在从 json 获取数据时在 React 上呈现 html 标签

[英]How to render html tag on React while fetching data from json

How to render HTML tag on React while fetching data from json.如何在从 json 获取数据时在 React 上渲染 HTML 标签。 In my json data contains <h2> tag but it fails to render <h2> tag.在我的 json 数据中包含<h2>标签,但无法呈现<h2>标签。

here is my code这是我的代码

const [items, setItems] = useState({"data" : `"<h2>hi</h2>, this is a car"`})
return (
        <div>
          <p>{items.data}</p>
        </div>
)

The output is coming as output 即将推出

"<h2>hi</h2>, this is a car"

but expected output should be但预计 output 应该是

hi ,this is a car,这是一辆车

You can use dangerouslySetInnerHTML for that purpose, read from the documentation:您可以为此目的使用dangerouslySetInnerHTML ,从文档中阅读:

dangerouslySetInnerHTML is React's replacement for using innerHTML in the browser DOM. dangerouslySetInnerHTML是 React 在浏览器 DOM 中使用innerHTML的替代品。

Try as the following:尝试如下:

function createMarkup(data) {
  return { __html: data };
}

return <div>
    <p><div dangerouslySetInnerHTML={createMarkup(items.data)} /></p>
</div>

Important note also from the docs:来自文档的重要说明:

In general, setting HTML from code is risky because it's easy to inadvertently expose your users to a cross-site scripting (XSS) attack.通常,从代码中设置 HTML 是有风险的,因为很容易无意中将您的用户暴露给跨站点脚本 (XSS) 攻击。 So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it's dangerous.因此,您可以直接从 React 设置 HTML,但您必须输入dangerouslySetInnerHTML的 SetInnerHTML 并使用__html键传递 object,以提醒自己这是危险的。

I hope this helps!我希望这有帮助!

If your data is static instead of setting it as a string set it as a JSX element and that should take care of rendering html如果您的数据是 static 而不是将其设置为字符串,请将其设置为 JSX 元素,并且应该负责呈现 html

const Data = () => (<><h2>hi</h2>, this is a car</>)
const [items, setItems] = useState({data : <Data />})
return (
   <div>
     <p>{items.data}</p>
   </div>
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM