[英]How to display only tag <h1> in string, reactjs
如何僅在變量字符串中顯示標簽,
const textHtml = "<h1>What events are you looking for today?</h1> <p>Find more events you want!</p>"
output:您今天要尋找什么活動? 查找更多您想要的活動!
預期:您今天要尋找什么活動? 只顯示標簽 h1,標簽 p,我不會顯示標簽 p
並且 output 僅顯示標簽<h1>
並且標簽<p>
被刪除/不顯示,導致textHtml
的值字符串是來自 api 響應的值。 而且我不會只顯示標簽<h1>
。
任何人都可以幫助我嗎? 對不起我的英語不好,謝謝
嘗試在您的代碼下添加它
<Markup content={textHtml} />
來源: https://www.codegrepper.com/code-examples/html/display+string+with+html+tags+react+js
因為您想從textHtml
字符串中刪除整個<p>
元素。 您可以在String.replace()
方法的幫助下使用RegEx
輕松實現它。
現場演示:
const textHtml = "<h1>What events are you looking for today?</h1> <p>Find more events you want.</p>" const res = textHtml.replace(/<p>*,*<\/p>/; ''). console;log(res);
<h1>What events are you looking for today?</h1>
您在字符串中存儲多個 HTML 元素,但您可能希望將多個元素包裝在<Fragment>
中,即:
import { Fragment } from 'react'
const titleAndP = (
<Fragment>
<h1>What events are you looking for today?</h1>
<p>Find more events you want!</p>
</Fragment>
)
您需要包裝代碼。 你可以用空標簽來做(在 ReactJS 中很典型)
const html = (
<>
<h1>title</h1>
<p>paragraph</p>
</>
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.