You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Antd Input转大写后保持光标在指定输入位置

解决Antd Input转大写时光标位置异常问题

问题描述

使用Antd的Form.Item和Input组件时,输入小写字符会被转为大写,但在已输入的大写内容前插入字符时,光标会自动跳到输入框末尾,无法停留在插入位置。

解决方案

直接修改输入框value会导致光标重置,需要在修改value前后手动记录并恢复光标位置。修改后的代码如下:

import React from "react";
import { Form, Input } from "antd";

const MyInputComponent: React.FC = () => {
  return (
    <Form.Item name="input" label="Input">
      <Input onInput={toUpperCase} />
    </Form.Item>
  );
};

export default MyInputComponent;

const toUpperCase = (
  event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>
) => {
  const target = event.target as HTMLInputElement;
  const value = target.value;

  if (typeof value !== "string") return;

  // 记录当前光标位置
  const cursorPosition = target.selectionStart;
  const newValue = value.toUpperCase();

  target.value = newValue;

  // 恢复光标到原位置
  target.setSelectionRange(cursorPosition, cursorPosition);
};

原理说明

  1. 修改输入框值前,通过target.selectionStart获取当前光标起始位置
  2. 将输入内容转为大写后重新赋值给输入框
  3. 使用target.setSelectionRange将光标恢复到之前记录的位置,确保光标停留在插入点

内容的提问来源于stack exchange,提问作者Mamunur Rashid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 04:00:09