简体   繁体   中英

How can i access this p tag content in react?

I have this obj, I want to access this p tag content and render it through props. Without dangrouslySetInnerHTML method. What should I've to do?

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>`
}

You could extract the text via DOMParser , then use usual JSX to render that text in a JSX paragraph.

 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>

I've used useMemo there because parsing seems like enough work it's worth memoizing and avoiding repeating.

I would use 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)

You can create a new element and pass it your content.para value, after use textContent on this new element. Like this:

const htmlNode = document.createElement('div')
htmlNode.innerHTML = content.para
const sanitizedContent = htmlNode.textContent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM