[英]Why does react not compile HTML present in a state
I set a default value of a state to be <b> Hey </b>
.我将 state 的默认值设置为<b> Hey </b>
。 Now when I rendered this state on the UI it printed the string instead of Hey wrote in bold.I want to know why it is not working.现在,当我在 UI 上渲染这个 state 时,它打印了字符串而不是用粗体写的 Hey。我想知道它为什么不起作用。 Why react is not able to interpret the html tag and show the appropriate output为什么 react 无法解释 html 标签并显示相应的 output
import { useState } from "react";
import "./styles.css";
export default function App() {
const [html, setHtml] = useState("<b>Hey</b>");
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<div>{html}</div>
</div>
);
}
Output:- Output:-
Was expecting the output to be Hey written in bold.期待 output 是用粗体写的嘿。
Here's the codesandbox link for better understanding:-https://codesandbox.io/s/heuristic-chaum-vo6qt?file=/src/App.js这是代码框链接,以便更好地理解:-https://codesandbox.io/s/heuristic-chaum-vo6qt?file=/src/App.js
Thank you.谢谢你。 I just want to know why react is not able to render the HTML tag as HTML tag instead of printing it out.我只是想知道为什么 react 不能将 HTML 标签呈现为 HTML 标签而不是打印出来。
Because you are rendering a string, not HTML.因为您正在渲染一个字符串,而不是 HTML。 If you want to render stringified HTML then use dangerouslySetInnerHTML , use caution what you pass through, in other words, you may want to run the string through a DOM purifier first.如果你想渲染字符串 HTML 然后使用dangerouslySetInnerHTML ,小心你通过什么,换句话说,你可能想先通过 DOM 净化器运行字符串。
export default function App() {
const [html, setHtml] = useState("<b>Hey</b>");
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<div dangerouslySetInnerHTML={{ __html: html}} />
</div>
);
}
You are setting the value of html
as "<b>Hey</b>"
which is a string string that's why it renders that as it is.您将html
的值设置为"<b>Hey</b>"
,这是一个字符串字符串,这就是它按原样呈现的原因。 You can directly assign html to the variable like so:您可以像这样直接将 html 分配给变量:
const [html, setHtml] = useState(<b>Hey</b>);
It's a string and not HTML, to fix that maybe you can insert it in the div as innerHTML
ie.它是一个字符串而不是 HTML,以解决这个问题,也许你可以将它作为innerHTML
插入到 div 中,即。
document.querySelector(".divClassName").innerHTML = html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.