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;
说明
inputRef是AntD Input专门用于获取原生input DOM的属性,通过它可以直接操作DOM的value属性设置默认值- 这种非受控的方式不会触发组件重渲染,完美适配你大型动态表单避免卡顿的需求,保存时直接读取
inputRef.current.value即可提交数据
内容的提问来源于stack exchange,提问作者Germán
相关产品推荐
相关产品推荐

