Reactjs iframe contentDocument在应用CSS覆盖时为空

Reactjs iframe contentDocument在应用CSS覆盖时为空,reactjs,typescript,Reactjs,Typescript,在将CSS应用于加载到iframe中的内容时,我遇到了一个问题。在componentdidmount中呈现iframe之后,我调用一个方法来更新内容文档以应用CSS覆盖。但是,contentdocument即将为空。尝试使用中间方法检查文档状态是否就绪,然后调用override方法,否则,调用相同的中间方法再次检查。但contentDocument总是为空 有没有一种方法可以在加载到iframe的内容上应用CSS,或者在contentDocument中获取值 这里是代码片段- private i

在将CSS应用于加载到iframe中的内容时,我遇到了一个问题。在componentdidmount中呈现iframe之后,我调用一个方法来更新内容文档以应用CSS覆盖。但是,contentdocument即将为空。尝试使用中间方法检查文档状态是否就绪,然后调用override方法,否则,调用相同的中间方法再次检查。但contentDocument总是为空

有没有一种方法可以在加载到iframe的内容上应用CSS,或者在contentDocument中获取值

这里是代码片段-

private iframeRef: React.RefObject<HTMLIFrameElement>;

constructor(props: IIframeViewProps) {
    super(props);
    this.iframeRef = React.createRef();
}

public async componentDidMount(): Promise < void> {
    this.updateContentDocument();
}


public render(): JSX.Element | null {
    return (
        <iframe
            aria-label='iframe content'
            src='any external URL'
            ref={this.iframeRef}
            width='100%'
            height='700px'
            // tslint:disable-next-line:react-iframe-missing-sandbox
            sandbox='allow-scripts allow-forms allow-same-origin'
        />
    );
}

private updateContentDocument = (): void => {

    if (this.iframeRef && this.iframeRef.current) {
        const innerDocument = this.iframeRef.current.contentDocument;
        const css = 'body h1{font-size:50px;color:red}';

        if (innerDocument) {
            innerDocument.open();

            if (css) {
                // Append custom style
                const style = document.createElement('style');
                const cssNote = document.createTextNode(css);
                style.type = 'text/css';
                style.appendChild(cssNote);
                innerDocument.head.appendChild(style);
            }

            innerDocument.close();
        }
    }
}
private iframeRef:React.reobject;
构造函数(道具:IIframeViewProps){
超级(道具);
this.iframeRef=React.createRef();
}
公共异步组件didmount():Promise{
这个.updateContentDocument();
}
public render():JSX.Element | null{
返回(
);
}
私有updateContentDocument=():void=>{
if(this.iframeRef&&this.iframeRef.current){
const innerDocument=this.iframeRef.current.contentDocument;
constcss='body h1{字体大小:50px;颜色:red}';
如果(内部文档){
innerDocument.open();
如果(css){
//附加自定义样式
const style=document.createElement('style');
const cssNote=document.createTextNode(css);
style.type='text/css';
风格。附属物子(cssNote);
innerDocument.head.appendChild(样式);
}
innerDocument.close();
}
}
}