如何在 React 中使用现有的预填充数据创建可编辑的表单输入
How to create editable form inputs with existing prefill data in React
我有一些数据和表单输入,我需要在字段中预填现有数据,点击编辑时我想编辑数据并将其提交到点击按钮时的状态
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>
// 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>
);
我有一些数据和表单输入,我需要在字段中预填现有数据,点击编辑时我想编辑数据并将其提交到点击按钮时的状态
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>
// 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>
);