reactjs - 使用useState在react js上单击提交后重置表单输入字段
问题描述
我有一个登录表单工作得很好,我想在单击提交后将输入字段设置为空白。我搜索了类似的问题,但大多数人都在使用 react hook 和其他我没有使用的东西,所以我不知道如何使这些解决方案适应我的。这是我的代码:
import React, { useState } from 'react';
import {
FormWrap,
Container,
Icon,
FormContent,
Form,
FormH1,
FormLabel,
FormInput,
Text,
FormButton,
TextLeft,
Heading,
Subtitle,
TextWrapper,
LogoPage,
ModalWrapper,
FormMiniLabel, Wrapper, FormInputTerms, TermLink, FormMiniLabelWarning}
from './SignInElements'
import Axios from 'axios'
import { Modal} from '../Modal/Modal';
const SignIn = ({}) => {
const[name, setname] = useState("");
const[cpf, setcpf] = useState("");
const[tel, settel] = useState("");
const[email, setemail] = useState("");
const[terms, setterms] = useState("");
const register = () => {
Axios.post('http://localhost:3001/register/', {
name: name,
cpf: cpf,
tel: tel,
email: email,
}).then((response) => {console.log(response)});
console.log(name);
console.log(cpf);
console.log(tel);
console.log(email);
console.log(terms);
};
const [showModal, setShowModal] = useState(false);
const OpenModal = () => {
setShowModal(prev => !prev);
};
function AllFunc() {
register();
OpenModal();
}
function SubmitButton(){
if (name && cpf && tel && email && terms){
return <FormButton type="submit" onClick={AllFunc}>Cadastrar</FormButton>
} else {
return (
<FormButton type="submit">Cadastrar</FormButton>)
};
};
return (
<>
<Container>
<FormWrap>
<FormContent>
<TextLeft action="#">
<Icon to="/"> <LogoPage src={require('../../images/Brand.svg').default} /> </Icon>
<TextWrapper>
<Heading>Bora parcelar com a Wowpen? </Heading>
<Subtitle>Cadastre-se completando o formulário e participe do nosso grupo seleto de beta testers. Tenha acesso antecipado a funcionalidade de parcelamento e interaja diretamente com o nosso time de desenvolvimento.</Subtitle>
</TextWrapper>
</TextLeft>
<Form action="#">
<FormLabel htmlFor="for">Como podemos te chamar?</FormLabel>
<FormInput placeholder="Nome Sobrenome" type="text" required 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 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 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 onChange={(e) => setemail(e.target.value) } />
<Wrapper>
<FormInputTerms type="checkbox" required onChange={(e) => setterms(e.target.value) } />
<FormMiniLabel>Li e concordo com os <TermLink>Termos e a Política de Privacidade</TermLink> da Wowpen. </FormMiniLabel>
</Wrapper>
<SubmitButton/>
</Form>
<Modal setShowModal={setShowModal} showModal={showModal}/>
</FormContent>
</FormWrap>
</Container>
</>
)
}
export default SignIn
基本上,有一个 SubmitButton 函数,当所有字段都填满时,它会触发为 MySQL 数据库(注册)发送数据并打开模式(openModal)的函数。我试图添加一个名为 reset 的函数,例如:
function reset () {
setname("");
settel("");
}
要在提交按钮单击时调用,但无法将字段设为空白。
表单组件如下(我正在使用样式组件):
export const Form = styled.form`
background: #fff;
background-image: url(${img});
background-size: 100% 100%;
background-position:center;
background-repeat:no-repeat;
max-width: 100%;
height: 100%;
width: 100%;
display: grid;
grid-area: col2;
padding: 80px 147px;
align-content: center;
@media screen and (max-width: 480px) {
padding: 32px 32px;
}
@media screen and (max-width: 700px) {
padding: 80px 60px;
height: 1200px;
width: 100%;
justify-content: center;
background-size: cover;
}
@media only screen and (min-width: 1500px) and (max-width: 1501px) {
height: 1200px;
width: 100%;
padding: 0;
justify-content: center;
}
`;
以及表单输入组件(也带有样式组件):
export const FormInput = styled.input`
padding: 16px 16px;
/*margin-bottom: 32px;*/
border: none;
height: 56px;
border-radius: 4px;
font-size: 18px;
background-color: #F6F6F6;
margin-bottom: 24px;
`;
有谁知道提交后如何将输入字段设置为空白?
解决方案
我已将所有输入更改为受控输入,因此每当您的状态更改时,它会自动反映在您的输入框中,也为所有 FromInputs 添加了值
<FormInput value={name} ...
所以在更改为受控元素后,您现在可以通过清除状态来清除文本框值
import React, { useState } from 'react';
import {
FormWrap,
Container,
Icon,
FormContent,
Form,
FormH1,
FormLabel,
FormInput,
Text,
FormButton,
TextLeft,
Heading,
Subtitle,
TextWrapper,
LogoPage,
ModalWrapper,
FormMiniLabel, Wrapper, FormInputTerms, TermLink, FormMiniLabelWarning}
from './SignInElements'
import Axios from 'axios'
import { Modal} from '../Modal/Modal';
const SignIn = ({}) => {
const[name, setname] = useState("");
const[cpf, setcpf] = useState("");
const[tel, settel] = useState("");
const[email, setemail] = useState("");
const[terms, setterms] = useState("");
const register = () => {
Axios.post('http://localhost:3001/register/', {
name: name,
cpf: cpf,
tel: tel,
email: email,
}).then((response) => {
console.log(response)
setname("");
settel("");
setcpf("");
setemail("");
setterms(false)
});
};
const [showModal, setShowModal] = useState(false);
const OpenModal = () => {
setShowModal(prev => !prev);
};
function AllFunc() {
register();
OpenModal();
}
function SubmitButton(){
if (name && cpf && tel && email && terms){
return <FormButton type="submit" onClick={AllFunc}>Cadastrar</FormButton>
} else {
return (
<FormButton type="submit">Cadastrar</FormButton>)
};
};
return (
<>
<Container>
<FormWrap>
<FormContent>
<TextLeft action="#">
<Icon to="/"> <LogoPage src={require('../../images/Brand.svg').default} /> </Icon>
<TextWrapper>
<Heading>Bora parcelar com a Wowpen? </Heading>
<Subtitle>Cadastre-se completando o formulário e participe do nosso grupo seleto de beta testers. Tenha acesso antecipado a funcionalidade de parcelamento e interaja diretamente com o nosso time de desenvolvimento.</Subtitle>
</TextWrapper>
</TextLeft>
<Form action="#">
<FormLabel htmlFor="for">Como podemos te chamar?</FormLabel>
<FormInput value={name} placeholder="Nome Sobrenome" type="text" required onChange={(e) => setname(e.target.value) }/>
<FormLabel htmlFor="for">Compartilha seu CPF?</FormLabel>
<FormMiniLabel>É importante para verificar sua identidade.</FormMiniLabel>
<FormInput value={cpf} placeholder="000.000.000-00" type="text" required 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 value={tel} placeholder="(DDD) 90000-0000" type="text" required onChange={(e) => settel(e.target.value) } />
<FormLabel htmlFor="for">E seu e-mail?</FormLabel>
<FormMiniLabel>Prometemos não enviar spam ;)</FormMiniLabel>
<FormInput value={email} placeholder="exemplo@email.com" type="email" required onChange={(e) => setemail(e.target.value) } />
<Wrapper>
<FormInputTerms checked={terms} type="checkbox" required 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>
<Modal setShowModal={setShowModal} showModal={showModal}/>
</FormContent>
</FormWrap>
</Container>
</>
)
}
export default SignIn
除了这种方法,我建议使用单个状态对象来处理所有值,例如const [data, setData] = useState({})
通过使用这种方法,您可以处理一个对象中的所有值,并且可以快速清除它
推荐阅读
- scikit-learn - 如何通过/跳过管道取决于特定条件
- c# - 如何解决 C# 中的简单变量问题?
- php - 如何使用存储的时间戳数据计算每个月的报告总数并以 json 数组格式输出
- angular - 通过 Effect 和 Service 更新 NgRX 存储数组
- android - 模拟器无法加载“libGLES_emulation”驱动程序
- c - C -- 在换行符上取消引用
- javascript - 发生构建错误 ReferenceError: describe is not defined > 在 now.sh 部署期间
- fortran - 加快阅读和打开文件的速度
- java - 如何将创建的文件保存到Java中用户指定的文件路径?
- c# - Swagger Ui 不在 asp.net mvc 上加载静态文件