我正在尝试使用axios post方法将新用户添加到我的数据库中,并使用我用材料ui制作的表单,该应用程序运行良好不会在控制台或浏览器中标记出任何错误,如果显示我表单,但是我不能写TextFields。
在添加函数之前,我可以写的很好,但是在添加Onchange和value之后,我不再让自己写
会发生什么?
组件
import React, { useState } from "react";
import axios from 'axios';
//useState hook create a state named user with initial state set to an object with name, lastname and age properties set to empty strings
function UserAdd(props) {
const initialState = { name: '', lastname: '', age:0 }
const [user, setUser] = useState(initialState)
function handleChange(event) {
setUser({...user, [event.target.name]: event.target.value})
}
function handleSubmit(event) {
event.preventDefault();
if(!user.name || !user.lastname || !user.age) return
async function postUser() {
try {
const response = await post('/api/addUser', user);
props.history.push(`/user/${response.data._id}`);
} catch(error) {
console.log('error', error);
}
}
postUser();
}
function handleCancel() {
props.history.push("/users");
}
return (
<div style={{ padding: 16, margin: 'auto', maxWidth: 1000 }}>
<Typography variant="h4" align="center" component="h1" gutterBottom>
Add User
</Typography>
<form onSubmit={handleSubmit} className={classes.container} >
<TextField
label="Name"
className={classes.textField}
value={user.name}
onChange={handleChange}
margin="normal"
variant="outlined"
/>
<TextField
id="filled-read-only-input"
label="Lastname "
className={classes.textField}
value={user.lastname}
onChange={handleChange}
margin="normal"
variant="outlined"
/>
<TextField
required
id="filled-required"
label="Age"
className={classes.textField}
value={user.age}
onChange={handleChange}
margin="normal"
variant="outlined"
/>
<Grid item style={{ marginTop: 30 }}>
<Button
variant="contained"
color="primary"
type="submit">
Add
</Button>
</Grid>
<Grid item style={{ marginTop: 30 }}>
<Button
onClick={handleCancel}
variant="contained"
type="cancel">
Cancel
</Button>
</Grid>
</form>
</div>
);
}
export default UserAdd;```
答案 0 :(得分:1)
您似乎需要具有name
属性才能与event.target.name
一起传递。不知道TextField
需要什么道具,但我想应该是这样的:
<TextField
name="name" // Add this
label="Name"
className={classes.textField}
value={user.name}
onChange={handleChange}
margin="normal"
variant="outlined"
/>
同样,您需要一个name
道具来支持其他输入组件。