简体   繁体   中英

React Render HTML Code (dangerouslySetInnerHTML?)

I am building an App where Serverinput is being rendered.

Now I am trying to figure out, how it´s possible to display pure HTML. Because now it is only displayed as ...., where it should show an Image.

The question is, where should one call dangerouslySetInnerHTML() here to display all HTML as requested?

The Strings are being stores in an Array(messageList) that is being mapped. Userinput is escaped, so theres no problem on that side.

  let listItems = messageList.map(d => (
   <div >
     <p className={d.senderId + "timestamp"}>{d.time}</p>
     <p className={d.senderId} key={d.idCount} ref={d.idCount}>
       {" "}
        {d.text}{" "}
    </p>
   </div>
 ));

  let gif1 = <img className="gif" alt="" src={gif} />;

  return (
    <div >
      <div dangerouslySetInnerHTML={__html: {listItems}} />
      <ul>{listItems}</ul>

    </div>
  );

Thanks a lot for any help that is given.

I updated the dangerousHTML where I thought it would work. But now it throws - Syntax error: Unexpected token, expected }

对于要显示动态内容的每个元素,您都应具有类似的内容

<div dangerouslySetInnerHTML={__html: {yourHtmlContent}} />

How I understood is that Array(messageList) contains a list of markup strings.

So you just need to join them.

const messageList = [
  "<h2>Header</h2>",
  "<body>This is body!</body>",
  "<footer>Footer!</footer>"
];

function createMarkup() {
  return { __html: messageList.join("") };
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

It'd display something like this 在此处输入图片说明

You need to pass a string not an object as you do here.
( as it's just an implementation of innerHTML )

{__html: {listItems}}

Full source for completeness.

import React, { Component } from "react";
import { render } from "react-dom";
import "./styles.css";

const messageList = [
  "<h2>Header</h2>",
  "<body>This is body!</body>",
  "<footer>Footer!</footer>"
];

function createMarkup() {
  return { __html: messageList.join("") };
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: "React"
    };
  }

  render() {
    return (
      <div>
        <MyComponent />
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

Working demo.
修改soanswer52225099

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