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

React中提交发送消息后如何清空文本输入框?尝试多种方法无效求解决

问题根因

  • 你使用的Material UI TextField 没有绑定value属性,属于半受控组件,就算你修改了绑定的message状态,也无法同步到输入框的显示上
  • 发送成功的回调中只清空了lastName,没有清空message、firstName等其他输入字段对应的状态
  • 代码中存在多处拼写不一致的问题,比如状态名firstename、函数名creatSend,容易导致状态更新失效

修复代码

// 修正状态命名拼写,避免调用错误
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [message, setMessage] = useState('');
const sendCollectionRef = collection(db, 'messages');
const [loader, setLoader] = useState(false);

const createSend = async () => {
  setLoader(true);
  try {
    await addDoc(sendCollectionRef, {
      Firstname: firstName,
      Lastname: lastName,
      Email: email,
      Message: message,
    })
    setLoader(false);
    // 清空所有输入字段对应的状态
    setFirstName('');
    setLastName('');
    setMessage('');
    alert('Your Message has been sent');
  } catch (error) {
    alert(error.message);
    setLoader(false);
  }
};

// TextField补充value属性绑定,实现完全受控
<TextField
  id="outlined-basic"
  label="Message"
  multiline
  rows={4}
  variant="outlined"
  placeholder="Type Your Message"
  fullWidth
  style={{ backgroundColor: '#2b2b2b' }}
  value={message}
  onChange={(event) => setMessage(event.target.value)}
/>
<Grid xs={12} item class="send-spacer">
  <LoadingButton
    onClick={createSend}
    endIcon={<SendIcon />}
    variant="contained"
    style={{
      background: loader ? '#ccc' : 'rgb(2, 2, 110)',
    }}
  />
</Grid>

内容的提问来源于stack exchange,提问作者Majd Kilou

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:06:05