所以,我很难解决这个问题。 基本上,我有一个与React Final Form不相关的组件,但位于 Form 标签内。主要方法是当用户单击按钮(在这种情况下为牙齿)时,其值会更改并用紫色填充以显示其是否被单击-如果未单击,则用白色填充。但是,当我填写表格并单击带有牙齿的组件时,整个表格会重新呈现。有什么办法可以处理这种行为?也许我弄错了,这与我的自定义组件有关。
代码有点大,所以我将举例说明它是如何构建的:
<Form
initialValues={exam}
onSubmit={onSubmit}
render={({ handleSubmit, form, submitting, pristine, values }) => (
<form onSubmit={handleSubmit}>
/*Custom component handling the teeth I mentioned*/
<ConeBeam onClick={toothClicked} color="white" data={teeth} />
/*TextField related to React-Final-Form using mui-rff*/
<TextField
label="Region"
name="clark_region"
size="small"
fullWidth
/>
</form>
)}
/>
/*toothClicked function*/
function toothClicked({ id }) {
const tooth = parseInt(id);
const el = document.getElementById(id);
if (!teeth.includes(tooth)) {
setTeeth([...teeth, tooth]);
el.setAttribute("class", classes.primary);
} else {
teeth.splice(teeth.indexOf(tooth), 1);
setTeeth([...teeth]);
el.setAttribute("class", classes.white);
}
}
已解决! 我正在使用useState,它重新渲染以更改其状态。刚刚使用let将setTeeth更改为一个简单变量。
答案 0 :(得分:0)
该表单将重新呈现,因为这就是React的工作方式-如果您更改组件的状态或道具,则该组件将重新呈现。如果重新提交是您的应用程序遇到的问题,请考虑将ConeBeam
组件移至父级。
答案 1 :(得分:0)
似乎您需要使用React.useCallabck()
进行回调,尤其是onSubmit
,这是Form
的一个支持,因此在每个父级重新渲染时,您的onSubmit
都会得到一个新的函数引用会导致重新呈现Form。
const Parent = () => {
const onSubmit = React.useCallback(() => {
// do your submit logic here
});
return (
<Form onSubmit={onSubmit} ... />
);
}