Rumah  >  Artikel  >  hujung hadapan web  >  Bagaimana untuk Memaparkan Rentetan HTML dengan Selamat dalam React Menggunakan dangerouslySetInnerHTML?

Bagaimana untuk Memaparkan Rentetan HTML dengan Selamat dalam React Menggunakan dangerouslySetInnerHTML?

Linda Hamilton
Linda Hamiltonasal
2024-11-15 00:34:02365semak imbas

How to Safely Render HTML Strings in React Using dangerouslySetInnerHTML?

Safely Rendering HTML Strings as HTML

In this scenario, the issue arises when attempting to render a normal string of HTML content, but it instead appears as a string without being interpreted as HTML. This is typically encountered when the property being used in dangerouslySetInnerHTML is an object rather than a string.

To resolve this, ensure that the this.props.match.description property is a string. If it's not, convert it to HTML before assigning it to the property.

Handling HTML Entities

Additional complications arise when dealing with HTML entities. In such cases, you'll need to decode the entities before passing them to dangerouslySetInnerHTML.

Example Code

Consider the following example code:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      description: '<p><strong>Our Opportunity:</strong></p>',
    };
  }

  htmlDecode(input) {
    const e = document.createElement('div');
    e.innerHTML = input;
    return e.childNodes.length === 0 ? '' : e.childNodes[0].nodeValue;
  }

  render() {
    return (
      <div
        dangerouslySetInnerHTML={{ __html: this.htmlDecode(this.state.description) }}
      />
    );
  }
}

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

In this example, the description property contains HTML entities (< and >). To render it correctly, the htmlDecode function is used to decode these entities before passing the HTML to dangerouslySetInnerHTML.

Atas ialah kandungan terperinci Bagaimana untuk Memaparkan Rentetan HTML dengan Selamat dalam React Menggunakan dangerouslySetInnerHTML?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn