admin管理员组文章数量:1125041
I'm working on a text editor where users can edit individual words, and I'm running into an issue with the cursor position resetting while typing. Each time a character is typed, the cursor jumps to the beginning of the word.
Here's a simplified version of my code:
const EditableWord = React.memo(({ text, onUpdate }) => {
const [localText, setLocalText] = useState(text);
const [selectionRange, setSelectionRange] = useState<Range | null>(null);
const storeCaret = useCallback(() => {
const selection = document.getSelection();
if (selection && selection.rangeCount > 0) {
setSelectionRange(selection.getRangeAt(0));
}
}, []);
const restoreCaret = useCallback(() => {
const selection = document.getSelection();
if (selection && selectionRange) {
selection.removeAllRanges();
selection.addRange(selectionRange);
}
}, [selectionRange]);
useEffect(() => {
restoreCaret();
}, [localText, restoreCaret]);
const handleInput = useCallback((e: React.FormEvent<HTMLSpanElement>) => {
storeCaret();
setLocalText(e.currentTarget.innerText);
}, [storeCaret]);
return (
<span
contentEditable
suppressContentEditableWarning
onInput={handleInput}
className="outline-none cursor-text">
{localText}
</span>
);
});
I'm trying to maintain the cursor position by storing and restoring the selection range, but it's not working correctly. Every time I type a character, the cursor jumps to the beginning of the contentEditable span. I've tried:
Storing the selection range before the update Restoring it after the text updates using useEffect Using React.memo to prevent unnecessary re-renders
But none of these approaches have solved the issue. What am I doing wrong, and how can I maintain the cursor position while typing in a contentEditable element in React?
版权声明:本文标题:reactjs - React contentEditable cursor position resets while typing in controlled component - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736655283a1946238.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论