我使用React-select在表单中进行选择,当我点击select并改变select的值时,其他字段输入字段的当前statevalue被清除,而在提交时我只得到select的值。
const [values, setValues] = useState({
username: "",
email: "",
time: "",
});
const handleChange = (event) => {
setValues({
...values,
[event.target.id]: event.target.value,
});
console.log(`Option entered:`, values);
};
const optionsTime = [
{
value: "15",
label: "15 mins",
},
{
value: "30",
label: "30 mins",
},
{
value: "45",
label: "45 mins",
},
{
value: "60",
label: "60 mins",
},
{
value: "75",
label: "75 mins",
},
];
const handleSubmit = (e) => {
e.preventDefault();
console.log(`Option submited:`, values);
alert("You are submitting " + values);
};
const handleTime = (e) => {
//I used created a different onChange function for react-select and used e.value because react select //throws error of undefined id or value when e.target.value is used...
if (values.time !== e.value) {
setValues({ time: e.value });
}
console.log(`Option selected:`, e, values);
};
return (
<div className="headerRow">
<Navbar />
<div className="col-lg-4 schedule-area d-none d-lg-block">
<form id="schedule" onSubmit={handleSubmit}>
<h3>Schedule A Brief</h3>
<div className="form-group">
<input
id="username"
type="text"
placeholder="Contact Person"
className="form-control"
onChange={handleChange}
value={values.username}
required
/>
</div>
<div className="form-group">
<input
id="email"
type="email"
placeholder="Email Address"
className="form-control"
onChange={handleChange}
value={values.email}
required
/>
</div>
<div className="form-group">
<Select
id="time"
type="options"
placeholder="Select Brief Time Projection"
onChange={handleTime}
options={optionsTime}
valueInput={values.time}
isSearchable
required
/>
</div>
<div onClick={handleSubmit} className="book_btn text-center">
Schedule a Brief
</div>
</form>
</div>
</div>
);
请问我该怎么做才能获得所有输入字段的值,包括选择字段onSubmit。
目前你只返回 时候 覆盖其他旧值 价值观 状况
替换
const handleTime = (e) => {
if (values.time !== e.value) {
setValues({ time: e.value });
}
至
const handleTime = (e) => {
if (values.time !== e.value) {
setValues((old)=>({...old, time: e.value })); }
我换了
const handleTime = (e) => {
if (values.time !== e.value) {
setValues({ time: e.value });
}
要。
const handleTime = (e) => {
if (values.time !== e.value) {
setValues({
...values,
time: e.value
});
}
现在更新了...