reactjs 如何在React中使用现有预填充数据创建可编辑表单输入

wbrvyc0a  于 2022-11-29  发布在  React
关注(0)|答案(1)|浏览(116)

我有一些数据和表单输入,我需要在字段中预填充现有数据,当单击编辑时,我喜欢编辑数据并将其提交到单击按钮时的状态

const data = {
  name: "nazar",
  email: "nazar@gmail.com",
  phone: 123456789
};

const [ editData, setEditData ] = useState()

function handleEdit(){
  
}

function handleSubmit(){
  
}
<form onChange={handleEdit}>
    <input type="text" name='name'/><button>Edit</button><br/>
    <input type="text" name='email'/><button>Edit</button><br/>
    <input type="text" name='phone'/><button>Edit</button><br/>
    <button type='submit' onSubmit={handleSubmit}>Submit</button>
</form>
yeotifhr

yeotifhr1#

// declare your data as initial state
 const [data, setData] = React.useState({
    name: 'nazar',
    email: 'nazar@gmail.com',
    phone: 123456789,
  });

  // handle on change according to input name and setState
  const handleChange = (e) => {
    setData({ ...data, [e.target.name]: e.target.value });
  };

  const handleSubmit = (e) => {
    e.preventDefault()
    // take data to submit
  };
  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          name="name"
          value={data.name}    // inject state correspond to input and so on
          onChange={handleChange}
        />
        <button>Edit</button>
        <br />
        <input
          type="text"
          name="email"
          value={data.email}
          onChange={handleChange}
        />
        <button>Edit</button>
        <br />
        <input
          type="text"
          name="phone"
          value={data.phone}
          onChange={handleChange}
        />
        <button>Edit</button>
        <br />
        <button type="submit">
          Submit
        </button>
      </form>
    </div>
  );

相关问题