Setting iframe height to scrollHeight in ReactJS

后端 未结 5 465
隐瞒了意图╮
隐瞒了意图╮ 2021-01-02 07:24
  • The typical solution to the problem doesn\'t work in in React due to its dynamically generated component structure and event model, as opposed to traditional static HT
5条回答
  •  被撕碎了的回忆
    2021-01-02 07:58

    What you want to do is in your componentDidMount, run the script to set the height. [If you are loading external content, you might want to add event listener on the IFrame to wait until the external content is loaded.]

       componentDidMount() {
           const obj = ReactDOM.findDOMNode(this);
           obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
        }
    

    There is another, more "reacty" way of doing this - where you would store the height in state.

       componentDidMount() {
           const obj = ReactDOM.findDOMNode(this);
           this.setState({iFrameHeight:  obj.contentWindow.document.body.scrollHeight + 'px'});
        }
    

    and then in your render:

    render() {
        return (
            
    {this.renderHTMLFrame()}
    ); }

提交回复
热议问题