首頁 > web前端 > js教程 > 如何使用危險的SetInnerHTML在React中安全地渲染HTML字串?

如何使用危險的SetInnerHTML在React中安全地渲染HTML字串?

Linda Hamilton
發布: 2024-11-15 00:34:02
原創
451 人瀏覽過

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.

以上是如何使用危險的SetInnerHTML在React中安全地渲染HTML字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板