javascript - 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>
</>
)
}
}
解决方案
您必须为此创建一个 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>
</>
)
}
}
推荐阅读
- python - 如何从字典中制作分组小提琴图
- swift - SwiftUI 无法追加到数组
- javascript - 未从甜蜜警报对话框中删除“确定”按钮
- github - 如何在 GITHUB 存储库中一次向多个用户/整个发起发送邀请而不是一一发送
- firebase - 验证服务器上的 Firebase 实例 ID
- c# - 用户名的 C# 正则表达式
- nginx - Nginx 中的 $http_host:$proxy_port 和 $host:$server_port 有什么区别
- hadoop - HIVE - 逃避双引号问题
- node.js - 使用节点 js 创建实时连接
- swift - 如何在第二个故事板中使图像视图填满 Swift 中的所有屏幕