WP API and React rendering HTML, not text

2019-08-02 15:24发布

问题:

I am creating a react wordpress blog. Right now I am sending a JSON request and getting all of the posts, this is working properly ) Once I have that I am creating a post object for each post.

I can properly display the title, image, etc. However when I try to display the content of the post using post.content.rendered ( i take the first 250 characters for a preview ) It is showing the actual html in the output for example instead of printing "Hello World" it is printing

<p>Hello World</p>

I am getting the json response successfully from: /wp-json/wp/v2/posts and i am returning the post info in the code below.

return (
    <article className="post-outer" id={post.id}>
      <section className="post-section">
        <a className="post-link">
          <div className="post-box" >
            <h1 className="post-title">
              {post.title.rendered}
            </h1>
            <p className="post-desc">
              {post.content.rendered.substring(0,250)}
            </p>
            </div>
          <figure className="media-wrapper"><img src={ this.state.media } /></figure>
        </a>
      </section>
    </article>
  )

回答1:

Use dangerouslySetInnerHTML to render html strings:

<div dangerouslySetInnerHTML={{ __html: post.content.rendered }} />

dangerouslySetInnerHTML is React's replacement for using innerHTML in the browser DOM, behind the scenes when you use dangerouslySetInnerHTML it lets React know that the HTML inside of that component is not something it cares about.

Check this example:

let a = "<p>Hello</p>";
let b = "<p>Hello";
let c = "<p>Hello<";
let d = "<p>Hello</";

class App extends React.Component{
   
   render(){
     return(<div>
       <div dangerouslySetInnerHTML={{__html: a}}></div>
       <div dangerouslySetInnerHTML={{__html: b}}></div>
       <div dangerouslySetInnerHTML={{__html: c}}></div>
       <div dangerouslySetInnerHTML={{__html: d}}></div>
      </div>
     )
   }
}

ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>


<div id='app'/>