Reactjs:完成对dangerouslySetInnerHTML的回调

时间:2017-06-14 16:47:27

标签: reactjs

我目前正在使用这样的React组件:

        <div id="product-content" className="bz">
            <a className="anchor" id="content-anchor"></a>
            <h2 className="title-section">Thông tin sản phẩm</h2>
            <div className="fixed-menu-content">
                <div className="container">
                    <ul>
                        <li><a href="#content-anchor">Thông tin sản phẩm</a></li>
                        <li><a href="javascript:void(0)">Video sản phẩm</a></li>
                        <li><a href="#rating-anchor">Đánh giá (19)</a></li>
                        <li><a href="#guide-anchor">Hướng dẫn mua hàng</a></li>
                    </ul>
                </div>
            </div>
            <div dangerouslySetInnerHTML={{__html: description}}></div>
        </div>

似乎危险的SetInnerHTML对组件生命周期没有影响。我将此行放在componentDidMount中,但它返回错误的结果:

let b = $("#product-content").height(); // wrong: 600, true: 6500

如果我尝试在控制台开发工具中运行上面的行,则返回true结果,因为组件已完全呈现。

如何触发dangerouslySetInnerHTML的回调?

2 个答案:

答案 0 :(得分:3)

看来DOMSubtreeModified事件已被弃用,而有利于Mutation Observer API

你可以重构lustoykov提出的使用新API的代码:

&#13;
&#13;
class ContentRenderer extends React.Component {
  componentDidMount() {
      this.observer = new MutationObserver(this.handleMutation);
      this.observer.observe(this.myElement, {
        // Check config in https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
        childList: true,
        attributes: true,
        characterData: true
      });
    }
  
    componentWillUnmount() { 
      this.observer.disconnect();
    }
    
    handleMutation() {
      console.log('mutation');
    }
    
    render() {
      return (
        <div 
          dangerouslySetInnerHTML={{ __html: "<div>Test</div>" }}
          ref={(myElement) => { this.myElement = myElement; }}
        />
      );
    }
  }
&#13;
&#13;
&#13;

答案 1 :(得分:2)

完成dangerouslySetInnerHTML没有回调,但您必须诉诸refsDOMSubtreeModified

 // use ref to get the DOM Node
 <div 
   dangerouslySetInnerHTML={{__html: description}}
   ref={myElement => this.myElement = myElement}
  >
 </div>

 // Listen for changes inside the DOM Node
 componentDidMount() { 
    this.myElement.addEventListener('DOMSubtreeModified', () => {
      // execute your logic here...
    });
 }

 // Don't forget to clean up the listener
 componentWillUnmount() { 
    this.myElement.removeEventListener('DOMSubtreeModified');
 }

PS。

  

对此事件(DOMSubtreeModified)要非常小心,如果您决定更改事件处理程序中的DOM,则很容易导致无限循环。