在 React 中渲染 HTML 字串
    
    Rana Hasnain Khan
    2024年2月15日
    
    React
    React Render
    
 
我們將介紹如何在 React 中渲染 HTML 字串和渲染轉義的 HTML 字串。
在 React 中渲染 HTML 字串
在大型網站上工作時,我們需要重用 HTML 元件。或者,當在 HTML 中處理 JSON 響應時,我們需要在 React 中呈現 HTML 字串。
讓我們舉個例子,渲染一個普通的 HTML 字串。首先,我們將建立一個 ID 為 root 的 div。
# react
<div id="root"></div>
然後,讓我們將 HTML 字串呈現給 root。
# react
class App extends React.Component {
constructor() {
    super();
    this.state = {
      TextRender: '<h1>This is a heading</h1><p> This is a paragraph.</p>'
    }
  }
  
  render() {
    return (
      <div dangerouslySetInnerHTML={{ __html: this.state.TextRender }} />
    );
  }
}
ReactDOM.render(<App />, document.getElementById('root'));
輸出:

在上面的例子中,我們渲染了一個 HTML 字串。但是如果我們嘗試渲染一個轉義的 HTML 字串,它會報錯。
讓我們嘗試渲染一個轉義的 HTML 字串。
# react
class App extends React.Component {
constructor() {
    super();
    this.state = {
      TextRender: '<h1>This is a heading</h1><p> This is a paragraph.</p>'
    }
  }
  
  render() {
    return (
      <div dangerouslySetInnerHTML={{ __html: this.state.TextRender }} />
    );
  }
}
ReactDOM.render(<App />, document.getElementById('root'));
輸出:

正如你在上面的示例中注意到的那樣,由於轉義的 HTML 字串,HTML 標記無法正確呈現。
現在,我們將建立一個 DecodeHtml 函式來將轉義的 HTML 字串轉換為普通的 HTML 字串。
# react
DecodeHtml(input){
    var a = document.createElement('div');
    a.innerHTML = input;
    return a.childNodes.length === 0 ? "" : a.childNodes[0].nodeValue;
  }
所以,程式碼應該是這樣的。
# react
class App extends React.Component {
constructor() {
    super();
    this.state = {
      TextRender: '<h1>This is a heading</h1><p> This is a paragraph.</p>'
    }
  }
  htmlDecode(input){
    var a = document.createElement('div');
    a.innerHTML = input;
    return a.childNodes.length === 0 ? "" : a.childNodes[0].nodeValue;
  }
  
  render() {
    return (
      <div dangerouslySetInnerHTML={{ __html: this.htmlDecode(this.state.TextRender) }} />
    );
  }
}
ReactDOM.render(<App />, document.getElementById('root'));
輸出應如下所示。
輸出:

通過這種方式,我們可以輕鬆渲染轉義的 HTML 字串。
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.
LinkedIn