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

React使用useState管理表单时点击提交后如何重置输入字段

你遇到的问题是两个核心点导致的:

  1. 你的输入组件是React受控组件,但没有绑定value/checked属性到对应的state,state更新后视图不会同步刷新
  2. 复选框的状态绑定逻辑有误,且你写的reset函数只重置了两个字段,没有覆盖所有表单值

步骤1:修正所有输入框的绑定逻辑

给所有FormInput组件添加value属性绑定对应state,复选框组件FormInputTerms改用checked绑定state,同时修改复选框的onChange取值逻辑,另外阻止表单默认提交刷新页面的行为:

<Form action="#" onSubmit={(e) => e.preventDefault()}>
  <FormLabel htmlFor="for">Como podemos te chamar?</FormLabel>
  <FormInput 
    placeholder="Nome Sobrenome" 
    type="text" 
    required 
    value={name}
    onChange={(e) => setname(e.target.value) }
  />
  <FormLabel htmlFor="for">Compartilha seu CPF?</FormLabel>
  <FormMiniLabel>É importante para verificar sua identidade.</FormMiniLabel>
  <FormInput 
    placeholder="000.000.000-00" 
    type="text" 
    required  
    value={cpf}
    onChange={(e) => setcpf(e.target.value) }
  />
  <FormLabel htmlFor="for">Qual seu número de Whatsapp?</FormLabel>
  <FormMiniLabel>Esse é nosso principal meio de comuniação.</FormMiniLabel>
  <FormInput 
    placeholder="(DDD) 90000-0000" 
    type="text" 
    required 
    value={tel}
    onChange={(e) => settel(e.target.value) } 
  />
  <FormLabel htmlFor="for">E seu e-mail?</FormLabel>
  <FormMiniLabel>Prometemos não enviar spam ;)</FormMiniLabel>
  <FormInput 
    placeholder="exemplo@email.com" 
    type="email" 
    required 
    value={email}
    onChange={(e) => setemail(e.target.value) } 
  />
  <Wrapper>
  <FormInputTerms 
    type="checkbox" 
    required 
    checked={terms}
    onChange={(e) => setterms(e.target.checked) }
  />
  <FormMiniLabel>Li e concordo com os <TermLink>Termos e a Política de Privacidade</TermLink> da Wowpen. </FormMiniLabel>
  </Wrapper>
  <SubmitButton/>
</Form>

步骤2:完善reset函数

修改reset函数覆盖所有表单字段:

function reset () {
   setname("");
   setcpf("");
   settel("");
   setemail("");
   setterms(false);
}

步骤3:调整提交逻辑

建议把重置、弹窗操作放到Axios请求的成功回调里,避免请求失败时用户还要重填表单:

const register = () => {
  return Axios.post('http://localhost:3001/register/',  {
      name: name,
      cpf: cpf,
      tel: tel,
      email: email,
  }).then((response) => {console.log(response)});
};

async function AllFunc() {
  await register();
  reset();
  OpenModal();
}

修改完成后提交表单即可正常清空所有输入字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 18:54:03