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?

本文标签: reactjsReact contentEditable cursor position resets while typing in controlled componentStack Overflow