米琪卡哇伊
2023-05-11 14:45:26
作為練習,我正在從頭開始構建博客。我將我的帖子正文存儲在 MongoDB 中,它存儲為一個巨大的字符串。我在該字符串中添加了一些隨機的 html 標簽以進行測試。解析那個長字符串以便讀取然后使用 html 標記的通常方法是什么?堆棧是:JavaScript / React / Express / MongoDB一些代碼: function Posts({ posts }) { const postLis = posts.map((post) => { return ( <li key={post._id}> <h1>{post.title}</h1> <p>{post.body}</p> </li> ); }); return <ul>{postLis}</ul>;}我的測試 JSON:{"posts": [{"_id": "5f7af2f468478387e792a522","title": "Welcome to Explore Edinburgh(express test 1)","featuredPhoto": "/432425521","date": "10th September 2020, 14:25","tags": ["edinburgh","explore edinburgh"],"body": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum condimentum, quam vel<br>porta porta, elit mauris viverra diam, et pharetra nisl lorem<br>eget neque."},
1 回答

慕田峪7331174
TA貢獻1828條經驗 獲得超13個贊
您可以執行以下操作:
function Posts({ posts }) {
? const postLis = posts.map((post) => {
? ? return (
? ? ? <li key={post._id}>
? ? ? ? <h1>{post.title}</h1>
? ? ? ? <p dangerouslySetInnerHTML={{ __html: post.body }}></p>
? ? ? </li>
? ? );
? });
? return <ul>{postLis}</ul>;
}
如果因為無法確保內容安全而要解析它,可以使用html-react-parser
:
use { parse } from 'html-react-parser';
function Posts({ posts }) {
? const postLis = posts.map((post) => {
? ? return (
? ? ? <li key={post._id}>
? ? ? ? <h1>{post.title}</h1>
? ? ? ? <p>{parse(post.body)}></p>
? ? ? </li>
? ? );
? });
? return <ul>{postLis}</ul>;
}
添加回答
舉報
0/150
提交
取消