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

AntD Input使用useRef设置默认值失效及表单性能优化问题

解决AntD Input使用useRef赋值默认值无效的问题

核心原因

AntD的Input组件是对原生input的封装,直接使用ref属性获取到的是AntD Input组件的实例,而非底层的原生input DOM元素。而MUI TextField、原生input的ref直接指向DOM节点,所以能通过ref.current.value赋值生效。

解决方案

使用AntD Input提供的inputRef属性来获取原生input的DOM引用,而非组件自身的ref。

代码示例

import { Input } from 'antd';
import { useRef, useEffect } from 'react';

function App() {
  const inputRef = useRef(null);

  useEffect(() => {
    // 模拟fetch获取默认值
    setTimeout(() => {
      if (inputRef.current) {
        inputRef.current.value = '从接口获取的默认值';
      }
    }, 1000);
  }, []);

  const handleSave = () => {
    const value = inputRef.current?.value;
    // 提交到服务器
    console.log('提交的值:', value);
  };

  return (
    <div>
      <Input inputRef={inputRef} placeholder="请输入内容" />
      <button onClick={handleSave}>保存</button>
    </div>
  );
}

export default App;

说明

  1. inputRef是AntD Input专门用于获取原生input DOM的属性,通过它可以直接操作DOM的value属性设置默认值
  2. 这种非受控的方式不会触发组件重渲染,完美适配你大型动态表单避免卡顿的需求,保存时直接读取inputRef.current.value即可提交数据

内容的提问来源于stack exchange,提问作者Germán

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 12:37:08