[英]How can i access this p tag content in react?
我有這個 obj,我想訪問這個 p 標簽內容,並通過 props 渲染它。 沒有 dangrouslySetInnerHTML 方法。 我該怎么辦?
let content = {
para: `<p>A listing page is the public view of a listing. It should informations be designed to display all relevant information about a listing.</p>`
}
您可以通過DOMParser
提取文本,然后使用通常的 JSX 在 JSX 段落中呈現該文本。
const { useMemo } = React; let content = { para: `<p>A listing page is the public view of a listing. It should informations be designed to display all relevant information about a listing.</p>`, }; const Example = ({ content }) => { const paragraph = useMemo(() => { const parser = new DOMParser(); const doc = parser.parseFromString(content.para, "text/html"); return <p>{doc.querySelector("p").textContent}</p>; }, [content]); return ( <div> Here's the paragraph: {paragraph} </div> ); }; const App = () => { return <Example content={content} />; }; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<App />);
<div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
我在那里使用useMemo
,因為解析似乎已經足夠了,值得記住並避免重復。
我會使用String.prototype.slice
let content = { para: `<p>A listing page is the public view of a listing. It should informations be designed to display all relevant information about a listing.</p>` } const text = content.para.slice(3, -4) console.log(text)
在這個新元素上使用textContent
之后,您可以創建一個新元素並將您的content.para
值傳遞給它。 像這樣:
const htmlNode = document.createElement('div')
htmlNode.innerHTML = content.para
const sanitizedContent = htmlNode.textContent
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.