Skip to content

Commit

Permalink
fix(textarea): fix autofocus cursor at the end (#3358)
Browse files Browse the repository at this point in the history
  • Loading branch information
HaixingOoO authored Feb 6, 2025
1 parent 94f628e commit 645858e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/textarea/Textarea.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,14 @@ const Textarea = forwardRef<TextareaRefInterface, TextareaProps>((originalProps,

useIsomorphicLayoutEffect(() => {
adjustTextareaHeight();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [textareaRef?.current]);
if (autofocus && textareaRef.current) {
const textarea = textareaRef.current;
textarea.focus();
// 将光标移到内容的末尾
textarea.selectionStart = textarea.value.length;
textarea.selectionEnd = textarea.value.length;
}
}, []);

useIsomorphicLayoutEffect(() => {
// 当未设置 autosize 时,需要将 textarea 的 height 设置为 auto,以支持原生的 textarea rows 属性
Expand Down
7 changes: 7 additions & 0 deletions src/textarea/__tests__/textarea.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,11 @@ describe('Textarea 组件测试', () => {
expect(changeValue).not.toBeNull();
expect(event).not.toBeNull();
});

test('autofocus cursor end', async () => {
const value = 'test autofocus';
const { container } = render(<Textarea value={value} autofocus />);

expect(container.getElementsByTagName('textarea')[0].selectionStart).toBe(value.length);
});
});

0 comments on commit 645858e

Please sign in to comment.