reactjs 如何在React js中使用输入字段的onChange阻止State对象更新

lymnna71  于 2023-01-08  发布在  React
关注(0)|答案(1)|浏览(148)

我正在尝试为我的应用程序创建多步骤注册表单。我正在将表单数据保存为"registerData"状态。
我在输入数据时遇到问题。每当我尝试在组件页面之一(例如page1,Name)中输入数据时,它会执行onChange并将Name从""更改为输入的字母,但在此之后,它会立即将"registerData"恢复为原始状态,并将所有属性设置为""。
下面是代码:
Register.js:

import React, {useState} from 'react';
import Page1 from './register_components/Page1';
import Page2 from './register_components/Page2';
import Page3 from './register_components/Page3';

function Register() {
  const [registerData, setRegisterData] = useState(
    {
      //Personal Details
      Name: "",
      LastName: "",
      Phone: "", //Null
      Birthday: "", //Null
      //Address
      Street: "",
      Zip: "",
      Building: "",
      House: "", //Null
      City: "",
      Voivodeship: "",
      //Login information
      Email: "",
      Password: ""
    }
  ) 

  const [ pageIndex, setPageIndex] = useState(0)
  const [ pages, setPages ] = useState([
    <Page1 registerData={registerData} setRegisterData={(data) => {setRegisterData(data)}}/>,
    <Page2 registerData={registerData} setRegisterData={(data) => {setRegisterData(data)}}/>,
    <Page3 registerData={registerData} setRegisterData={(data) => {setRegisterData(data)}}/>
  ])

  const PrevPage = () =>{
    if (pageIndex <= 0)
      return
    setPageIndex(pageIndex - 1)
  }

  const HandleSubmit = (event) => {
    event.preventDefault();
    if (pageIndex !== pages.length - 1){
      setPageIndex(pageIndex + 1)
      return
    }

    console.log("Submmited")
  }

  return (
    <div className="App">
      <h1>Rejestracja</h1>

      <form className='register-form' onSubmit={HandleSubmit}>
        {pages[pageIndex]}
        {pageIndex !== 0 && <button type="button" onClick={ () => {PrevPage()}}>Poprzedni</button>}
        <button type="submit">{pageIndex !== pages.length - 1? "Nastepny" : "Przeslij"}</button>
      </form>

    </div>
  );
}

export default Register;

Page1.js

import React from 'react'

export default function Page1({registerData, setRegisterData}) {
    console.log("rerender")
    console.log(registerData)
  return (
    <div>
        <input
            placeholder='Imie'
            required type='text'
            value={registerData.Name}
            onChange={(e) => { setRegisterData({...registerData, Name: e.target.value}); console.log(e.target.value) }}
        />
        
        <input
            placeholder='Nazwisko'
            required
            type='text'
            value={registerData.LastName}
            onChange={(e) => { setRegisterData({...registerData, LastName: e.target.value}) }}
        />
        
        <input
            placeholder='Nr telefonu'
            required
            type='text'
            value={registerData.Phone}
            onChange={(e) => { setRegisterData({...registerData, Phone: e.target.value}) }}
        />
        
        <div className='date-form'>
            <label>Data urodzenia</label>
            <input
                type='date'
                value={registerData.Date}
                onChange={e => { setRegisterData({...registerData, Birthday: e.target.value}) }}
            />
        </div>
    </div>
  )
}

由于我对react没有太多的经验,所以我很难判断,但我认为问题在于Register.js在每次更改"registerData"状态时都会重新呈现,这会导致它恢复到原始值。

gwo2fgha

gwo2fgha1#

试着把它作为一个onChange值的函数...它对你很有帮助。其次,在你的input标签中添加带有相同状态对象名称的name属性。

    • 例如:**
const [registerData, setRegisterData] = useState(
{
    //Personal Details
    Name: "",
    LastName: "",
    Phone: "", //Null
    Birthday: "", //Null
    //Address
    Street: "",
    Zip: "",
    Building: "",
    House: "", //Null
    City: "",
    Voivodeship: "",
    //Login information
     Email: "",
     Password: ""
   }
 ) 

  const handleFormChange = (index, event) => {
   let data = [...inputFields];
   data[index][event.target.name] = event.target.value;
   setInputFields(data);
 };

<div>
      <input
          placeholder='Imie'
          required type='text'
          name="Name"
          value={registerData.Name}
          onChange={(event) => handleFormChange(index, event)}
      />
    
    <input
        placeholder='Nazwisko'
        required
        type='text'
            name="LastName"
            value={registerData.LastName}
           onChange={(event) => handleFormChange(index, event)}
      />
    
   
      </div>
  </div>

相关问题