Javascript TypeError:无法读取属性';内容窗口';未定义的
我正在尝试使用React.js创建一个富文本编辑器,我正在使用iframe,并将designMode属性设置为“ON”。我想在单击按钮时将所选文本加粗。我想使用execCommand()函数,但我一直遇到这样的错误:TypeError:无法读取未定义的属性“contentWindow”。我是React的初学者,无法解决此问题 我已附上我的代码供您参考Javascript TypeError:无法读取属性';内容窗口';未定义的,javascript,reactjs,Javascript,Reactjs,我正在尝试使用React.js创建一个富文本编辑器,我正在使用iframe,并将designMode属性设置为“ON”。我想在单击按钮时将所选文本加粗。我想使用execCommand()函数,但我一直遇到这样的错误:TypeError:无法读取未定义的属性“contentWindow”。我是React的初学者,无法解决此问题 我已附上我的代码供您参考 import React, { Component } from 'react' import 'font-awesome/css/font-aw
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>
</>
)
}
}
import React,{Component}来自“React”
导入'font-awesome/css/font-awesome.css'
导出默认类编辑器扩展组件{
构造函数(){
超级()
this.execComd=this.execComd.bind(this)
}
componentDidMount(){
让编辑器=this.textField.contentWindow.document
editor.designMode='on'
}
execomd(命令){
this.textField.contentWindow.execCommand(command,false,null)
}
render(){
返回(
this.textField=textField}
id=“textField”
name=“textField”
样式={{宽度:“1000px”,高度:“500px”}
frameborder=“1”>
)
}
}
您必须为此创建一个绑定的引用,。例如构造函数内部的this.myRef=React.createRef()。然后在渲染方法中指定该属性
ref={this.myRef}
在ESC命令中,您现在可以拥有:
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>
</>
)
}
}
import React,{Component}来自“React”
导出默认类编辑器扩展组件{
构造函数(){
超级()
this.execComd=this.execComd.bind(this)
this.myRef=React.createRef();
}
componentDidMount(){
}
execomd(命令){
控制台日志(“已启动”);
log(this.myRef.current.contentWindow);
}
render(){
返回(
this.execomd('bold')}>单击
)
}
}
您正在调用this.execComd
并将结果指定为事件处理程序。此时,this.textField
还没有设置,这也不是您想要做的。你的意思大概是this.execComd('bold')}>
我有99%的把握。它显示了一个错误:“无法读取null的属性'contentWindow'”@AmoghDixit检查我添加的代码。它正确地预先设置了内容窗口。您的onClick处理程序有一些问题,您需要在那里定义一个函数,而不是调用它。