[英]How to parse string in react to render html
我正在構建一個帶有 MERN 堆棧的非常基本的博客類型應用程序,並且已經達到了我可以發布非常簡單的純文本帖子的程度。 任何人都可以建議我如何解析該字符串以在我的內容中也呈現 HTML 嗎?
所以帖子看起來像
帶有鏈接的粗體文本
代替
<b> Bold Text with <a href="#"> a link</a></b>
我的一個想法是嘗試在組件中使用DOMParser
,比如
const parser = new DOMParser();
const parsedContent = parser.parseFromString(post.description, 'text/html');
// and then in the render just print it out
<div className='content'>
{parsedContent}
</div>
那當然是行不通的,因為它返回了整個html
object 並且Objects are not valid as a React child.. if you meant to render a collection of children, use an array instead.
解析該字符串並在我的內容中呈現 HTML 的正確方法是什么?
你可以試試這樣:
const Test = () => {
const text = '<b> Bold Text with <a href="#"> a link</a></b>';
return <div dangerouslySetInnerHTML={{ __html: text }} />;
};
export default Test;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.