【问题标题】:React input radio won't update checked反应输入收音机不会更新检查
【发布时间】:2021-09-28 19:59:44
【问题描述】:

我的问题:

我正在尝试制作一个带有两个选项的简单收音机,当我设置字段的状态时,检查的值应该更新但它没有。 检查输入中使用的条件似乎没问题,但输入不会交替

我的代码:

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

【问题讨论】:

    标签: reactjs forms state


    【解决方案1】:

    setState需要像这样返回新值

    setForm((oldForm) => {
      return { ...oldForm, Tipo: event.target.value };
    });
    

    【讨论】:

    猜你喜欢
    • 2017-11-20
    • 2015-10-22
    • 2021-04-22
    • 2016-05-29
    • 2010-12-20
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    相关资源
    最近更新 更多