英文:
How do I convert a string to HTML won't work
问题
以下是翻译好的部分:
这段代码有什么问题?最初,我尝试渲染数组的元素。但它只显示为字符串,而不是应该显示为 HTML。所以我尝试使用来自以下代码的转换方法:
https://www.learnbestcoding.com/post/84/string-to-html-in-react-js
第二种方法,使用 HTML-react-parser npm 包。但不幸的是,我遇到了以下问题:
已编译出现问题:
错误
[eslint]
src/App.js
第 4 行:36: 'string' 未定义 no-undef
第 9 行:1: 模块体中的导入;重新排序到顶部 import/first
第 10 行:1: 模块体中的导入;重新排序到顶部 import/first
第 11 行:1: 模块体中的导入;重新排序到顶部 import/first
第 23 行:5: 'arrs_list' 未定义 no-undef
第 32 行:11: 'html' 未定义 no-undef
以下是 App.js 文件的一部分:
import React, { useEffect, useState } from "react";
import parse from 'html-react-parser';
export const StringToHtml = () =>{
const [html, setHtml] = useState<string>("")
useEffect(() => {
setHtml("<div>Html 存储为字符串</div>")
}, [html])
}
function App() {
const [val, setVal] = useState(0);
const word = 1;
const [arrs_list,setarrs]=useState(['<input type="text"/>'])
return (
<div className="App">
...
<br></br>
{arrs_list.map( (arr,index)=>
(
<p key={index}>{arr}</p>
)
)}
<>
{parse(html)}
</>
<div></div>
</div>
);
}
export default App;
希望这有助于你解决问题。如果你有任何其他问题,请随时提出。
英文:
tWhat is wrong with this code? Originally I had the element of an array render. But it was just diplaying as a string not as HTML as it should so I tried to convert using code from,
https://www.learnbestcoding.com/post/84/string-to-html-in-react-js
the second type, Using HTML-react-parser npm package. But unfortunately I'm getting
Compiled with problems:X
ERROR
[eslint]
src/App.js
Line 4:36: 'string' is not defined no-undef
Line 9:1: Import in body of module; reorder to top import/first
Line 10:1: Import in body of module; reorder to top import/first
Line 11:1: Import in body of module; reorder to top import/first
Line 23:5: 'arrs_list' is not defined no-undef
Line 32:11: 'html' is not defined no-undef
Here is part of the App.js file.
import React, { useEffect, useState } from "react";
import parse from 'html-react-parser';
export const StringToHtml = () =>{
const [html, setHtml] = useState<string>("")
useEffect(() => {
setHtml("<div>Html stored as a string</div>")
}, [html])
}
function App() {
const [val, setVal] = useState(0);
const word = 1;
const [arrs_list,setarrs]=useState(['<input type="text"/>'])
return (
<div className="App">
...
<br></br>
{arrs_list.map( (arr,index)=>
(
<p key={index}>{arr}</p>
)
)}
<>
{parse(html)}
</>
<div></div>
</div>
);
}
export default App;
As the site suggests I installed html-react-parser in the terminal.
答案1
得分: 1
你可以使用 dangerouslySetInnerHTML
:
<div style={{ display: 'contents' }} dangerouslySetInnerHTML={{ __html: html }}></div>
英文:
You can use dangerouslySetInnerHTML
:
<div style={{display: 'contents'}} dangerouslySetInnerHTML={{__html: html}}></div>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论