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
相关产品推荐
相关产品推荐

