反应输入收音机不会更新检查
React input radio won't update checked
我的问题:
我正在尝试制作一个带有两个选项的简单收音机,当我设置该字段的状态时,选中的值应该会更新,但实际上并没有。
输入内部检查中使用的条件似乎没问题,但输入不会交替
我的代码:
import { FormEvent, useState } from "react"
function CadastroGeral(){
const [form, setForm] = useState({
Tipo: "Comércio",
RazaoSocial: "",
NomeFantasia: ""
})
function handleSubmit(event: FormEvent){
event.preventDefault()
console.log(form)
}
async function handleChangeTipo(event: any){
await setForm(oldForm => {
oldForm.Tipo = event.target.value
return oldForm
})
console.log(form) //the data comes out updated
}
//other handlers here, all of them work just fine
return(
<div className="wrapper-page">
<form onSubmit={handleSubmit} className="content-container form-agendamento">
<div className="w-10 form-group">
<h1>Selecione seu tipo</h1>
<span>
<input type="radio" value="Comércio" checked={form.Tipo === 'Comércio'} onChange={handleChangeTipo}/>
Comércio
</span>
<span>
<input type="radio" value="Indústria" checked={form.Tipo === 'Indústria'} onChange={handleChangeTipo}/>
Indústria
</span>
</div>
<div className="w-10">
<input type="text" className="w-5" placeholder="Razão Social" onChange={handleChangeRazaoSocial}/>
<input type="text" className="w-5" placeholder="Nome Fantasia" onChange={handleChangeNomeFantasia}/>
</div>
<button className="btn btn-primary" type="submit">
Enviar
</button>
</form>
</div>
)
}
export default CadastroGeral
setState
需要 return 这样的新值
setForm((oldForm) => {
return { ...oldForm, Tipo: event.target.value };
});
我的问题:
我正在尝试制作一个带有两个选项的简单收音机,当我设置该字段的状态时,选中的值应该会更新,但实际上并没有。 输入内部检查中使用的条件似乎没问题,但输入不会交替
我的代码:
import { FormEvent, useState } from "react"
function CadastroGeral(){
const [form, setForm] = useState({
Tipo: "Comércio",
RazaoSocial: "",
NomeFantasia: ""
})
function handleSubmit(event: FormEvent){
event.preventDefault()
console.log(form)
}
async function handleChangeTipo(event: any){
await setForm(oldForm => {
oldForm.Tipo = event.target.value
return oldForm
})
console.log(form) //the data comes out updated
}
//other handlers here, all of them work just fine
return(
<div className="wrapper-page">
<form onSubmit={handleSubmit} className="content-container form-agendamento">
<div className="w-10 form-group">
<h1>Selecione seu tipo</h1>
<span>
<input type="radio" value="Comércio" checked={form.Tipo === 'Comércio'} onChange={handleChangeTipo}/>
Comércio
</span>
<span>
<input type="radio" value="Indústria" checked={form.Tipo === 'Indústria'} onChange={handleChangeTipo}/>
Indústria
</span>
</div>
<div className="w-10">
<input type="text" className="w-5" placeholder="Razão Social" onChange={handleChangeRazaoSocial}/>
<input type="text" className="w-5" placeholder="Nome Fantasia" onChange={handleChangeNomeFantasia}/>
</div>
<button className="btn btn-primary" type="submit">
Enviar
</button>
</form>
</div>
)
}
export default CadastroGeral
setState
需要 return 这样的新值
setForm((oldForm) => {
return { ...oldForm, Tipo: event.target.value };
});