React应用中contenteditable获取textContent时出现undefined错误
React中contenteditable输入框获取文本时出现TypeError错误
错误信息
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>
错误原因
问题出在onInput事件的参数传递逻辑:
handleChangeCode函数的第二个参数预期接收事件对象event,但实际回调中直接传递了e.currentTarget.textContent(即输入框的文本内容)。- 此时函数内的
event变量是字符串类型,字符串没有currentTarget属性,因此访问event.currentTarget.textContent时会抛出「无法读取undefined的textContent属性」的错误。
解决方案
两种修复方式任选其一即可:
方式一:传递事件对象,保留原处理函数逻辑
修改onInput的回调,直接传递事件对象e:
<blockquote // 其他属性保持不变 onInput={e => handleChangeCode(idx, e)} />
方式二:调整处理函数参数,直接接收文本内容
修改handleChangeCode函数,让第二个参数直接接收文本值:
function handleChangeCode(i, textContent) { const codeValues = [...createCode]; codeValues[i].value = textContent; setCreateCode(codeValues); console.log(codeValues); }
对应的JSX部分保持原传递方式即可:
onInput={e => handleChangeCode(idx, e.currentTarget.textContent)}
额外优化:contenteditable元素的回显处理
contenteditable元素的value属性不会生效,若需要回显状态中的值,需将code.value || ""作为元素的子节点:
<blockquote // 其他属性保持不变 contenteditable='true' > {code.value || ""} </blockquote>
内容的提问来源于stack exchange,提问作者soccerway
相关产品推荐
相关产品推荐

