首页 > 解决方案 > TypeError:无法读取未定义的属性“contentWindow”

问题描述

我正在尝试使用 React.js 制作富文本编辑器,并且我正在使用 iframe 并将 designMode 属性设置为“ON”。我想在单击按钮时使选定的文本变为粗体。我想使用 execCommand() 函数,但我不断收到此错误:TypeError:无法读取未定义的属性“contentWindow”。我是 React 的初学者,我无法弄清楚如何解决这个问题。

我附上了我的代码供您参考。

import React, { Component } from 'react'
import 'font-awesome/css/font-awesome.css'


export default class Editor extends Component {

    constructor(){
        super()
        this.execComd = this.execComd.bind(this)
    }

    componentDidMount(){
       let editor = this.textField.contentWindow.document
       editor.designMode = 'on'
    }

    execComd(command){
        this.textField.contentWindow.execCommand(command, false, null)   
    }

    render() {
        return (
            <> 
                <div>
                    <button onClick={this.execComd('bold')}><i className="fa fa-bold"></i></button>
                </div>
                <iframe 
                    ref={textField => this.textField = textField} 
                    id="textField" 
                    name="textField" 
                    style={{width: "1000px",height: "500px"}} 
                    frameborder="1">
                </iframe>
            </>
        )
    }
}

标签: javascriptreactjs

解决方案


您必须为此创建一个 ref 绑定。例如this.myRef = React.createRef(),在构造函数内部。然后在 render 方法中分配它。

ref={this.myRef}

在 escCommand 中,您现在可以拥有:

execComd(command){
       this.myRef.current.contentWindow.execCommand(command, false, null)   
    }

要创建我的提案的工作演示,请忽略,因为我删除了一些我不知道的不需要的代码:

import React, { Component } from 'react'


export default class Editor extends Component {

    constructor(){
        super()
        this.execComd = this.execComd.bind(this)
        this.myRef=React.createRef();
    }

    componentDidMount(){
      
    }

    execComd(command){
      console.log("fired");
      console.log(this.myRef.current.contentWindow);
    
    }

    render() {
        return (
            <> 
                <div>
                    <button onClick={()=>this.execComd('bold')}>Click<i className="fa fa-bold"></i></button>
                </div>
                <iframe 
                    ref={this.myRef} 
                    title="hello"
                    id="textField" 
                    name="textField" 
                    style={{width: "1000px",height: "500px"}} 
                    frameborder="1">
                </iframe>
            </>
        )
    }
}

推荐阅读