e.p preventdefault不是函数(React)



我使用React制作一个表单,将使POST到MongoDB,发生的事情是,当我开始尝试填写表单时,我得到以下错误:

e.preventDefault is not a function

TypeError: e.p preventdefault不是一个函数在handleChange

这是代码(以摘要形式),这是handleChange和handlessubmit:

const handleChange = (e) => {
e.preventDefault();
setProject({ ...project, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
const res = await fetch("http://localhost:5001/client/projects", {
method: "POST",
body: JSON.stringify(project),
headers: { "Content-Type": "application/json" },
});
const data = await res.json(project);
console.log(data);
console.log(project);
};

这里是表单的一小部分:

<form onSubmit={handleSubmit}>
<Box width="50%">
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DatePicker
id="project_start"
name="project_start"
value={project.project_start}
onChange={handleChange}
slotProps={{
textField: {
size: "small",
margin: "dense",
},
}}
/>
<DatePicker
id="project_end"
name="project_end"
value={project.project_end}
onChange={handleChange}
renderValue={(selected) => {
return [{ selected }];
}}
slotProps={{
textField: { size: "small", margin: "dense" },
}}
/>
</LocalizationProvider>
<TextField id="nombreP" margin="dense" size="small" />
<FormControl size="small" sx={{ m: 1 }}>
<Select
id="encargadoP"
multiple
name="usersId"
value={project.usersId}
onChange={handleChange}
MenuProps={MenuProps}
renderValue={(selected) => (
<Box sx={{ display: "flex", flexWrap: "wrap", gap: 0.5 }}>
{selected.map((value) => (
<Chip key={value} label={value} />
))}
</Box>
)}
sx={{ width: 205 }}
>
{data?.map(({ _id, name }) => (
<MenuItem key={_id} value={name}>
{name}
</MenuItem>
))}
</Select>
</FormControl>
</Box>
</Box>
<Button
type="submit"
variant={"outlined"}
size={"large"}
sx={{
width: 420,
border: "1px solid white",
m: "3rem 0 0 0",
color: "white",
borderRadius: "30px",
}}
>
Agregar proyecto
</Button>
</Box>
</form>

我非常感谢每一个能帮助我的人:)

MUI的DatePickeronChange回调将以新值作为第一个参数调用,而不是事件对象。

因此你的代码应该像这样修改:
const handleChange = (name, newVal) => {
setProject({ ...project, [name]: newVal });
};
<DatePicker id="project_start" name="project_start" value={project.project_start}
onChange={handleChange.bind(null, 'project_start')}/>
{ /* and so on for the other DatePickers ... */ }

相关内容

  • 没有找到相关文章

最新更新