How to get a React component's innerHTML

ぐ巨炮叔叔 提交于 2020-05-07 03:49:49

问题


I have a react component and I want its innerHTML to pass as prop to an iframe.

render() {
        const page = <PrintPage />
        const iframeContent = page..something...innerHTML
        return (
            <iframe srcDoc={iframeContent}/>);
}

Is there any way for doing like this.

I want to render only within the iframe, so i can't use ref. I want the innerHTML of component which is not mounted


回答1:


You can use refs or ReactDOM.findDOMNode to get innerHTML but the component should be mounted.

class App extends React.Component{

  componentDidMount(){
    console.log(this.ref.innerHTML)
    console.log(ReactDOM.findDOMNode(this).innerHTML)
  }
  render(){
    return (
      <div ref={r=>this.ref = r}>app</div>
    )
  }
}

ReactDOM.render(
  <App />,document.getElementById("app")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>


来源:https://stackoverflow.com/questions/45456644/how-to-get-a-react-components-innerhtml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!