如何在 Next JS 应用程序中将字符串转换为 HTML 元素?
Posted
技术标签:
【中文标题】如何在 Next JS 应用程序中将字符串转换为 HTML 元素?【英文标题】:How to convert String into a HTML element in Next JS Applcation? 【发布时间】:2021-07-06 03:31:05 【问题描述】:我已将产品描述作为 html 元素保存到这样的数据库中。但是当我将这些数据渲染到 div 中时,它显示为字符串。我想在 Next JS 应用程序 中显示所有数据,例如 HTML 元素。我试过 JSON.parse,但它不起作用。
如果有人能帮我解决这个问题,我们将不胜感激。
"images": [
"alternativeText": "cinnamon",
"path": "public/uploads/5585.jpg"
],
"_id": "606c39c884372a0e20c3f9bb",
"name": "Cinnamon",
"code": "5586",
"price": 49,
"category":
"_id": "6064b37855bd0f26e0df4616",
"name": "Natural Essential Oils",
"createdAt": "2021-03-31T17:38:00.066Z",
"updatedAt": "2021-03-31T17:38:24.398Z",
"__v": 0
,
"description": "<p>Cinnamon Bark Vitality™ essential oil has a warm, spicy flavor that complements a variety of classic culinary treats and drinks. Cinnamon Bark Vitality is not only great for elevating dishes, but it can also be taken as a dietary supplement and is an important ingredient in some of Young Living’s most popular products, including Thieves® Vitality™ and Inner Defense™. Cinnamon Bark Vitality’s warm taste and nostalgic notes bring a spicy addition to your favorite dishes. By using Cinnamon Bark Vitality as a dietary supplement, you can help support healthy digestive and immune systems.</p>",
"createdAt": "2021-04-06T10:36:56.440Z",
"updatedAt": "2021-04-06T10:36:56.440Z",
"__v": 0
检查图片附件。
Next Js 应用代码
const Product = (product) =>
return (
<Fragment>
<Head>
<title>Product</title>
</Head>
<Layout>
<div className="container-fluid product-page">
<div className="page-body">
<div className="row product">
<div className="col-xl-5 col-lg-5 image-box">
<div className="preview-image">
<div className="image">
<img
src=ImageRootPath + "/" + product.images[0].path
alt=product.images[0].alternativeText
/>
</div>
</div>
</div>
<div className="col-xl-7 col-lg-7 info-box">
<div className="product-info">
<div className="product-name">
<h4>product.name</h4>
<p>"Product code: " + product.code</p>
<hr/>
</div>
<div className="product-price">
<h5>Price: <span>product.price + "$"</span></h5>
<p>"Quantity: 5ml"</p>
</div>
<div className="product-des">
product.description
</div>
</div>
</div>
</div>
</div>
</div>
</Layout>
</Fragment>
);
【问题讨论】:
显示为 HTML 元素是什么意思?必须显示 HTML 标签,是这个意思吗? 【参考方案1】:因为你想显示原始 HTML,所以这个
<div className="product-des">
product.description
</div>
应该改为
<div className="product-des" dangerouslySetInnerHTML= __html: product.description >
official doc 对此进行了介绍
dangerouslySetInnerHTML
是 React 在浏览器 DOM 中使用innerHTML
的替代品 [...] 你必须输入dangerouslySetInnerHTML
并传递 一个带有__html
键的对象 p>
您还必须注意在这种情况下设置原始 HTML 的风险
一般来说,从代码中设置 HTML 是有风险的,因为很容易在不经意间让您的用户受到跨站脚本 (XSS) 攻击
【讨论】:
感谢您的帮助以上是关于如何在 Next JS 应用程序中将字符串转换为 HTML 元素?的主要内容,如果未能解决你的问题,请参考以下文章
在 Javascript 中将对象 Promise 转换为字符串
如何在服务器端渲染中将样式应用于 Next.js 中的 HTML?