繁体   English   中英

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

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

我想在单击按钮时使选定的文本变为粗体。 我想使用 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> )

请帮忙。

看起来这可能是因为您将调用execCmd() function 的结果分配给onClick属性 - 而不是预期的实际 ZC1C425268E68385D1AB5074C17A94F4 表达式。 在这种情况下, execCmd('bold')表达式甚至在 DOM 实际有机会被挂载之前就被评估。

尝试这样的事情:

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

暂无
暂无

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

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