簡體   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