在react js上使用useState点击submit后重置表单输入字段



我有一个在表单工作只是很好,我想设置输入字段空白后点击提交。我搜索了类似的问题,但大多数人都在使用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("");
}

要在提交按钮上调用,但它不能使字段为空。

表单组件在下面(我使用style -components):

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;
}
`;

和Form Input组件(也有style -components):

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;
`;

有谁知道我如何在提交后将输入字段设置为空白?

我已将所有输入更改为受控输入,因此每当您的状态更改时,它也会自动反映在您的输入框中为所有fromput添加值<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({}),通过使用这个方法,你可以处理一个对象中的所有值,并且可以快速清除它

您需要将onSubmit添加到Form标签

<Form action="#" onSubmit={onSubmit}>

然后创建一个函数,在点击Submit按钮

后执行
const onSubmit = e => {
e.preventDefault()
// do something

setname("");
settel("");
}

最新更新