3 回答

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超5個(gè)贊
那是因?yàn)槟鶬Form在當(dāng)前組件內(nèi)定義為 A 組件,這是不正確的。所以你有兩個(gè)解決方案。
1 - 移出IFORM Component當(dāng)前反應(yīng)。
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 聲明為當(dāng)前組件內(nèi)的普通函數(shù)。
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貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
原因是 IForm 組件是在 MyForm 組件內(nèi)部聲明的。這意味著每當(dāng) MyForm 組件的狀態(tài)發(fā)生變化時(shí),它都會(huì)刷新其 dom 樹(shù)。當(dāng) dom 重新渲染功能組件時(shí),IForm 將再次執(zhí)行,這就是為什么你總是會(huì)失去輸入的焦點(diǎn),但永遠(yuǎn)不會(huì)失去 MyForm 組件的狀態(tài)。
要阻止這種情況發(fā)生,請(qǐng)?jiān)?MyForm 組件外部聲明 IForm 組件,或者將 IForm 的 jsx 移至 MyFOrm 組件的 Return 內(nèi)部。

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超18個(gè)贊
你應(yīng)該只是setCommentForm
價(jià)值。我認(rèn)為你不需要傳播 prevState。
您想要實(shí)現(xiàn)的是將狀態(tài)值設(shè)置為新值。
還有,你沒(méi)有useEffect
權(quán)利嗎?
添加回答
舉報(bào)