【前端——bug】使用antd的Input组件无法通过ref修改value

问题背景

我要制作个人博客的chatgpt聊天页面,为了样式统一,我使用了antd的input组件,并且添加了ref属性获取当前输入的内容。我的预期效果是

  • 向输入框输入完成后,按下enter,把输入框置空
javascript 复制代码
const message = ref.current.input.value.trim();
ref.current.input.value = '';

<Input type="text" ref={ref} className={styles.userInput} placeholder="Type a message..."  onPressEnter={sendMessage} />

这里有一个坑就是,antd的input组件时封装html的,所以不能简单通过ref.current.value获取当前的内容,要再加一个input。

以上实践后发现,我enter后确实置空了,但是我对input框失焦或者再次点击后,值又回到上一次enter前的值

思考

- antd Input不要直接通过ref修改,因为当值发生改变时,必须在onChange中通过useState改变值,然后引发组件的重新渲染(可以使用ref来访问input元素,而改变ref的current属性的值时,不会导致重新渲染)

https://github.com/ant-design/ant-design/issues/18030

https://juejin.cn/post/7165804525431832612

解决办法

使用hooks来更新input的值

javascript 复制代码
const [inputValue, setInputValue] = React.useState('');
const message = inputValue.trim();
setInputValue('');

<Input type="text" placeholder="Type a message..."  onPressEnter={sendMessage} value={inputValue} onChange={(e) => setInputValue(e.target.value)} />
相关推荐
Penge66624 分钟前
《Go 后端开发者学 TypeScript:数组和元组》
javascript
Penge6661 小时前
《Go 后端开发者学 TypeScript:export关键字大全》
javascript
Penge6661 小时前
《Go 后端开发者学 TypeScript:从零理解 async、await 与 Promise》
javascript
Penge6661 小时前
typescript 中const用法
javascript
Csvn2 小时前
Monorepo
前端
Csvn2 小时前
流水线
前端
Csvn2 小时前
微前端架构
前端
该学习了咕咕2 小时前
顶刊论文学习笔记
学习
来让爷抱一个3 小时前
Python 异步里混用同步库,事件循环被卡住的全过程
开发语言·python
Linux-lucky3 小时前
45-Linux学习之旅之防火墙与WEB加固
linux·前端·网络·学习·ubuntu