3 回答

TA貢獻1811條經驗 獲得超5個贊
那是因為您IForm在當前組件內定義為 A 組件,這是不正確的。所以你有兩個解決方案。
1 - 移出IFORM Component當前反應。
function MyForm() {
const [commentForm, setCommentForm] = React.useState({
Comment: ""
});
const onCommentChange = (obj) => {
setCommentForm((prevState) => {
return {
...prevState,
...obj
};
});
};
return (
<div>
<IForm commentForm={commentForm} onCommentChange={onCommentChange} />
</div>
);
}
export default MyForm;
const IForm = ({ commentForm, onCommentChange }) => (
<Table>
<CardBody>
<Row>
<Col className="col-2">
<Label>Comment: </Label>
</Col>
<Col className="col-1">
<Input type="text"
value={commentForm.Comment}
onChange={(e) =>
onCommentChange({ Comment: e.target.value })} />
</Col>
</Row>
</CardBody>
</Table>
);
2 - 將 IForm 聲明為當前組件內的普通函數。
function MyForm() {
const [commentForm, setCommentForm] = React.useState({
Comment: ""
});
const onCommentChange = (obj) => {
setCommentForm((prevState) => {
return {
...prevState,
...obj
};
});
};
const form = () => (
<Table>
<CardBody>
<Row>
<Col className="col-2">
<Label>Comment: </Label>
</Col>
<Col className="col-1">
<Input type="text"
value={commentForm.Comment}
onChange={(e) =>
onCommentChange({ Comment: e.target.value })} />
</Col>
</Row>
</CardBody>
</Table>
);
return <div> {form()} </div>;
}
export default MyForm;

TA貢獻1796條經驗 獲得超4個贊
原因是 IForm 組件是在 MyForm 組件內部聲明的。這意味著每當 MyForm 組件的狀態發生變化時,它都會刷新其 dom 樹。當 dom 重新渲染功能組件時,IForm 將再次執行,這就是為什么你總是會失去輸入的焦點,但永遠不會失去 MyForm 組件的狀態。
要阻止這種情況發生,請在 MyForm 組件外部聲明 IForm 組件,或者將 IForm 的 jsx 移至 MyFOrm 組件的 Return 內部。

TA貢獻1853條經驗 獲得超18個贊
你應該只是setCommentForm
價值。我認為你不需要傳播 prevState。
您想要實現的是將狀態值設置為新值。
還有,你沒有useEffect
權利嗎?
添加回答
舉報