我具有以下组件,可在弹出窗口中添加评论。我想将汽车传递给组件以更新一些值,然后关闭弹出窗口,并更新从父级传递来的对象。
当我尝试更新汽车对象并尝试将其初始化为新数组或更新任何项目时,出现错误,提示其只读
这是我的代码
interface ICar
{
id: string;
comments: IComment[];
}
interface IComment
{
name: string;
comments: string;
}
const carComment = (car: ICar) => {
const [comm, setComm] = useState<string>("");
if (comm === "" && car.comments !== undefined && car.comments.length > 0) {
setComm(car.comments[0].comment);
}
const handleSaveClick = () => {
if (car.comments !== undefined && car.comments.length > 0) {
car.comments[0].comment = comm;
}
else {
car.comments = new Array<IComment>();
car.comments.push({ comment: comm, name: "Peter" });
}
return (
<>
<TextField
id="testMulti"
label="Comment"
multiline
rows={4}
defaultValue={comm}
variant="outlined"
key={1}
onChange={e => {
setComm(e.target.value);
}
}
/>
<Button onclick ="handleSaveClick"> Save </Button>
</>
}
}
export default CarComment;
答案 0 :(得分:0)
我在父级中添加了
const updateCar = (carComments: IComment[]) => {
...
};
<carComment id={props.id} comments={props.comments} updateCarCallback={updateCar}></carComment>
在我添加的孩子中
interface ICarCommentProps extends ICar {
updateCarCallback(carComments: IComment[]): void;
}
and in the handleSaveClick i added
updateCar(car.comments);