希望你过得好!我有一个小问题打破了我的头,我不知道如何解决它。我正在使用React,TypeScript,Ant Design和Refine Framework,并且有一个页面组件edit.tsx,我必须在其中编辑一条记录,因此,取决于来自字段catHasParent的DB的值可能是true或false,开关catHasParent将是Yes或Not,并且必须启用或禁用Form.Item > category_id Select,当catHasParent等于false时,category_id必须重置为null,并且必须将此值保存在DB上。如果我选择catHasParent为True并选择一个Parent Category,然后在不保存的情况下关闭catHasParent,那么catecory_id仍然是以前的值(错误地选择了错误的category_id),这就是我的问题,我找不到如何重置它。这是我的代码,干杯!
import React, { useState, useEffect } from "react";
import { IResourceComponentsProps } from "@refinedev/core";
import { Edit, useForm } from "@refinedev/antd";
import { Form, Row, Col, Input, Select, Switch } from "antd";
import { usePopulateSelect } from "../../components/populateSelect";
// Some declarations here
export const CategoryEdit: React.FC<IResourceComponentsProps> = () => {
...
const { form, queryResult, formProps, saveButtonProps } = useForm();
...
const [disabled, setDisabled] = useState(catHasParent);
const [catHasParent, setCatHasParent] = useState(false);
...
const optionsCategories = usePopulateSelect({ resource: "categories", data: categoryData });
...
let catHasParentValue = queryResult?.data?.data.catHasParent;
...
const toggle = () => {
setDisabled(!disabled);
setCatHasParent(!catHasParent);
// if (disabled) {
// Some code could be here but doesn't work
// }
};
return (
<Edit saveButtonProps={saveButtonProps} title="Edit Category">
<Form {...formProps} layout="vertical">
// Row and Col with Category Name and other stuffs
<Row gutter={{ xs: 8, sm: 16, md: 24, lg: 32 }}>
<Col className="gutter-row" flex={2}>
<Form.Item
label="Has a Parent Category?"
name={["catHasParent"]}
initialValue={catHasParentValue} // With this here I found that represent DB value
>
<Switch
defaultChecked={catHasParentValue} // With this here I found that represent DB value
checkedChildren="Yes"
unCheckedChildren="Not"
onClick={toggle}
/>
</Form.Item>
</Col>
<Col className="gutter-row" flex={20}>
<Form.Item
label="Category"
name={["category_id"]}
>
<Select
value={category_id}
options={optionsCategories}
disabled={catHasParent}
/>
</Form.Item>
</Col>
</Row>
// Others Rows and Cols with Information
</Form>
</Edit>
);
};
我测试检索记录从数据库和工作正常,该组件检索所有数据.选择类别可以很好地检索所有类别记录。开关启用和禁用Select Category_ID井。我研究了onFinish useForm状态和nothing。
1条答案
按热度按时间rjee0c151#
我准备了一个示例,演示如何动态禁用、更改和重置表单值。我希望我正确理解了你的问题。
https://codesandbox.io/p/sandbox/affectionate-sammet-plf6rq?embed=1&file=%2Fsrc%2Fpages%2Fposts%2Fedit.tsx%3A16%2C5