Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/471.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 通过React中的道具在iframe中显示html内容_Javascript_Reactjs_Iframe - Fatal编程技术网

Javascript 通过React中的道具在iframe中显示html内容

Javascript 通过React中的道具在iframe中显示html内容,javascript,reactjs,iframe,Javascript,Reactjs,Iframe,我有一个非常简单的可重用组件,用于显示通过道具传递的一些HTML export class HtmlPreview extends React.Component { componentDidMount() { this.rendered.contentDocument.body.innerHTML = this.props.body; } render() { return( <div> <iframe ref={(if

我有一个非常简单的可重用组件,用于显示通过道具传递的一些HTML

export class HtmlPreview extends React.Component {
  componentDidMount() {
    this.rendered.contentDocument.body.innerHTML = this.props.body;
  }
  render() {
    return(
      <div>
        <iframe ref={(iframe) => this.rendered}></iframe>
      </div>
    );
  }
}
导出类HtmlPreview扩展了React.Component{
componentDidMount(){
this.rendered.contentDocument.body.innerHTML=this.props.body;
}
render(){
返回(
这个.rendered}>
);
}
}
如图所示,我将此组件称为:

<HtmlPreview body={'<h1>Hello World</h1>'}/>

然而,如果没有抱怨
.contentDocument
不存在于未定义的对象中,我总是得到一个没有内容的空白iframe


非常感谢您的建议。

您为什么要使用iframe?您可以使用iframe显示另一个URL,例如

import React from 'react';

const HtmlPreview = ({ url }) => <iframe src={url} title="myIframe" />;

export default HtmlPreview;
从“React”导入React;
常量HtmlPreview=({url})=>;
导出默认HtmlPreview;
如果只想显示HTML预览,可以使用带有滚动条的div:

import React from 'react';

const HtmlPreview = ({ children }) => (
  <div style={{ width: 200, height: 200, overflowY: 'scroll' }}>{children}</div>
);

export default HtmlPreview;
从“React”导入React;
常量HtmlPreview=({children})=>(
{儿童}
);
导出默认HtmlPreview;
并按如下方式使用:

<HtmlPreview><h1>My Preview</h1></HtmlPreview>
我的预览

作为Scott,我也不了解iframe的ide。作为道具传递的html是普通字符串吗?如果是,您应该使用“危险的Html”。

我没有将
iframe
引用分配给组件内部的变量

iframe ref={(iframe) => this.rendered = iframe}></iframe>
iframe ref={(iframe)=>this.rendered=iframe}>
这允许在类方法中设置
This.rendered
内容