reactjs iframe not showing html



我需要在iframe中显示一个html页面。我正在使用 fetch 来获取内容,因为该页面具有身份验证。 我没有收到任何错误,也没有看到任何内容

someFunc() {
  const myIframe = this.refs.myIframe;     
  fetch('http://example.com/example.html', {
    method: 'GET',
    headers: {
      'Content-Type': 'text/html',
      'Authorization': 'Basic xyz'
    }
  }).then(function(response) {
      return response.text();
  }).then(function(text){
      //assign srcDoc to text
      return <iframe srcDoc={text}></iframe>;
  });
}
render() {
   return (<div>{this.someFunc()}</div>)
}

你为什么不做:<iframe src="http://example.com/example.html"></iframe>

否则,它不起作用的原因是在返回函数后执行 then。所以你可以做的是创建一些状态子级,并在 then 函数中设置它并在渲染函数中渲染它:

    var Example = React.createClass({
 componentDidMount: function() {
   var setState = this.setState;
   const myIframe = this.refs.myIframe;     
  fetch('http://example.com/example.html', {
    method: 'GET',
    headers: {
      'Content-Type': 'text/html',
      'Authorization': 'Basic xyz'
    }
  }).then(function(response) {
      return response.text();
  }).then(function(text){
    setState({child: <iframe srcDoc={text}></iframe>});
  });
},
 getInitialState: function() {
   return {child: <div> hello </div>};
 },
render: function() {
   return (<div>{this.state.child}</div>)
}
});
React.render(
  <Example />, 
  document.getElementById('mount-point'));

最新更新