如何向对象添加状态值?
How to add a state value to an Object?
我想将描述文本字段中的值添加到对象的值属性中。 value={description} 存储在状态 [description, setDescription] 中。
有人可以帮助如何将它正确地实现到 handleCreate 函数中吗??
export const Dialog: React.FC<DialogProps> = ({allTasks, setAllTasks}) =>{
const queryClient = useQueryClient();
const [open, setOpen] = useState(false);
const [description, setDescription] = useState("");
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
const handleCreate =(description: any)=>{
const addObjectToArray = (task: any) => {
setAllTasks ((allTasks: any) => [...allTasks, task]);
};
addObjectToArray({
description: description,
})
setOpen(false);
};
return (
<div>
<Dialog open={open} onClose={handleClose}>
<DialogTitle>Add New Task</DialogTitle>
<DialogContent>
<Box sx={{width: 500}}>
<TextField
id="description-text-field"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</Box>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Cancel</Button>
<Button onClick={handleCreate}>Create</Button>
</DialogActions>
</Dialog>
</div>
)}
试试这个代码:
const handleCreate = (description: any) => {
const addObjectToArray = (task: any) => {
setAllTasks([...allTasks, task]);
};
我想将描述文本字段中的值添加到对象的值属性中。 value={description} 存储在状态 [description, setDescription] 中。 有人可以帮助如何将它正确地实现到 handleCreate 函数中吗??
export const Dialog: React.FC<DialogProps> = ({allTasks, setAllTasks}) =>{
const queryClient = useQueryClient();
const [open, setOpen] = useState(false);
const [description, setDescription] = useState("");
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
const handleCreate =(description: any)=>{
const addObjectToArray = (task: any) => {
setAllTasks ((allTasks: any) => [...allTasks, task]);
};
addObjectToArray({
description: description,
})
setOpen(false);
};
return (
<div>
<Dialog open={open} onClose={handleClose}>
<DialogTitle>Add New Task</DialogTitle>
<DialogContent>
<Box sx={{width: 500}}>
<TextField
id="description-text-field"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</Box>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Cancel</Button>
<Button onClick={handleCreate}>Create</Button>
</DialogActions>
</Dialog>
</div>
)}
试试这个代码:
const handleCreate = (description: any) => {
const addObjectToArray = (task: any) => {
setAllTasks([...allTasks, task]);
};