【问题标题】:Adjust a field in a SimpleForm's value调整 SimpleForm 值中的字段
【发布时间】:2021-04-12 07:30:41
【问题描述】:

我有一个 React Admin Edit 表单,其中包含一个默认情况下不存在于记录中的字段。我可以手动输入,保存它,它会工作。但是,我希望在用户单击按钮然后对其进行调整时以编程方式检索该字段的值。

我使用 useMutation 挂钩来访问自定义 API,该 API 执行昂贵的操作并返回字段的结果。我只想在用户单击按钮时执行此操作。 所以在编辑表单中,我有一个名为 key 的字段,我想将来自这个 useMutation 挂钩的数据应用到它。

export const PostEdit = (props) => (
  <Edit title={<PostTitle />} {...props}>
    <SimpleForm>
      <TextInput disabled source="id" />
      <RetrieveKey />
      <TextInput source="key" />
    </SimpleForm>
  </Edit>
);

RetrieveKey 按钮是这样的

const RetrieveKey = ({ record }) => {
  const [retrieve, { loading }] = useMutation(
    {
      type: "retrieveKey",
      resource: "posts",
      payload: { id: record.id }
    },
    {
      onSuccess: ({ data }) => {
        if (data) {
          // Set the key field here.
        } else {
          console.log("No Key");
        }
      },
      onFailure: (error) => console.log("Error");
    }
  );
  return (
    <Button
      onClick={retrieve}
      disabled={loading}
      label={"Retrieve Key"}
    ></Button>
  );
};

我查看了各种表单挂钩,但找不到任何可以让我完成此任务的文档。 请注意,我不想立即调用 UpdateMethod,否则这将是微不足道的,我可以使用 DataProvider useUpdate 来调用它。相反,我想从响应的键中为用户预先填写表单。
这里提供了一个代码框:https://codesandbox.io/s/nifty-firefly-k13g7?file=/src/App.js

【问题讨论】:

    标签: react-admin


    【解决方案1】:

    我需要访问底层的 React-Final-Form API 才能编辑表单。

    React-Admin 文档在这里简要介绍一下:https://marmelab.com/react-admin/Inputs.html#linking-two-inputs

    所以在这种情况下,我需要使用 useForm 钩子,然后我可以更新表单值。

    const RetrieveKey = ({ record }) => {
      const form = useForm();
      const [retrieve, { loading }] = useMutation(
        {
          type: "retrieveKey",
          resource: "posts",
          payload: { id: record.id }
        },
        {
          onSuccess: ({ data }) => {
            console.log(form);
            
            if (data) {
              form.change("key", data);
            } else {
              console.log("No Key found");
            }
          },
          onFailure: (error) =>  console.log("Error");
        }
      );
      return (
        <Button
          onClick={retrieve}
          disabled={loading}
          label={"Retrieve Key"}
        ></Button>
      );
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-06
      相关资源
      最近更新 更多