代码之家  ›  专栏  ›  技术社区  ›  soccerway

内容可编辑抛出,无法读取react应用程序中未定义的属性(读取“textContent”)

  •  1
  • soccerway  · 技术社区  · 2 年前

    我正试图从我的react应用程序中的内容可编辑字段中键入文本内容,但出现以下错误;

    Uncaught TypeError: Cannot read properties of undefined (reading 'textContent')
        at handleChangeCode (admin.js:53:1)
        at onInput (admin.js:157:1)
        at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
        at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
        at invokeGuardedCallback (react-dom.development.js:4277:1)
        at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:1)
        at executeDispatch (react-dom.development.js:9041:1)
        at processDispatchQueueItemsInOrder (react-dom.development.js:9073:1)
        at processDispatchQueue (react-dom.development.js:9086:1)
    
    
    
    const [createCode, setCreateCode] = useState([{ value: null }]);
    
       function handleChangeCode(i, event) {
            const codeValues = [...createCode];
            codeValues[i].value = event.currentTarget.textContent;
            setCreateCode(codeValues);
            console.log(codeValues);
        }
    
    
            <div className='row'>
                {createCode.map((code, idx) => {
                      return (
                         <div key={`${code}-${idx}`} className="dCodeArea">
                            <button type="button" onClick={() => handleRemoveCode(idx)} 
                            className="closeElement">
                             X
                           </button>
                             <blockquote
                               type="text"
                               id="blogCode"
                               contenteditable='true'
                               className="codehighlight"
                               placeholder="Enter your code here"
                               value={code.value || ""}
                           onInput={e => handleChangeCode(idx, e.currentTarget.textContent)}
                             />
                             </div>
                         );
                     })}
              </div>
    
    1 回复  |  直到 2 年前
        1
  •  2
  •   tao    2 年前

    你在期待 event 作为的第二个参数 handleChangeCode 但你用它来称呼它 event.currentTarget.textContent .

    传递的字符串没有 .currentTarget (=> undefined ),以及 未定义 无法查询属性。

    简而言之,使用:

    <blockquote onInput={e => handleChangeCode(idx, e) />