简体   繁体   English

在 React.js 中使用 execCommand 时无法读取未定义的属性“contentDocument”

[英]Cannot read property 'contentDocument' of undefined when using execCommand in React.js

I want to make the selected text bold on click of a button.我想在单击按钮时使选定的文本变为粗体。 I want to use the execCommand() function but I keep getting this error: TypeError: Cannot read property 'contentDocument' of undefined.我想使用 execCommand() function 但我不断收到此错误:TypeError:无法读取未定义的属性“contentDocument”。

 import React, { useEffect } from 'react' import "./MainText.css" import "./App.css"; import FormatColorFillIcon from '@material-ui/icons/FormatColorFill'; import BorderColorIcon from '@material-ui/icons/BorderColor'; function MainText() { function enableEditMode() { const textpart = document.getElementsByName('textPart')[0]; const iframeDocument= textpart.contentDocument || textpart.contentWindow.document; iframeDocument.designMode = "on"; iframeDocument.contentEditable = true; } useEffect(() => { enableEditMode(); }, []) function execCmd(command) { const textpart = document.getElementsByName('textPart')[0]; const iframeDocument= textpart.contentDocument || textpart.contentWindow.document; iframeDocument.execCommand(command, false, null); } return ( <div className="mainText"> <button onClick={execCmd('bold')}><i class="fa fa-bold"></i></button> <div className="mainText__second"> <iframe name="textPart" frameBorder="0" ></iframe> </div> </div> )

please help in this.请帮忙。

It looks like this may be because your are assigning the result of calling the execCmd() function to the onClick property - rather than an actual function expression as is expected.看起来这可能是因为您将调用execCmd() function 的结果分配给onClick属性 - 而不是预期的实际 ZC1C425268E68385D1AB5074C17A94F4 表达式。 In this case the execCmd('bold') expression is evaluated even before the DOM actually has a chance to be mounted.在这种情况下, execCmd('bold')表达式甚至在 DOM 实际有机会被挂载之前就被评估。

Try something like this instead:尝试这样的事情:

onClick={() => execCmd('bold')}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM