简体   繁体   English

如何在 react-admin 中访问自定义组件中的表单数据?

[英]How to access form data in custom components in react-admin?

I need to change the behaviour of a toolbar button depending on a status field of the form.我需要根据表单的状态字段更改工具栏按钮的行为。 I don't know how to get access to the current form data to read the status value.我不知道如何访问当前表单数据以读取状态值。

I tried with FormDataConsumer in the surrounding component ( Toolbar in my case) and pass formData as a prop, but that had the side effect that handleSubmitWithRedirect inside the button did not work.我尝试在周围的组件中使用FormDataConsumer (在我的例子中是Toolbar )并将 formData 作为道具传递,但这有副作用, handleSubmitWithRedirect内的handleSubmitWithRedirect不起作用。

I'd like to read form data directly inside the button component.我想直接在按钮组件内读取表单数据。 How can I do this?我怎样才能做到这一点?

The current code:当前代码:

// ------------------------------------------------------------------------------------------
const StatusButton= ({ handleSubmitWithRedirect, ...props }) => {
    const form = useForm();

    const handleClick = useCallback(() => {
        switch (props.formdata.status.id) {   
            case 0:
                form.change('status', status[1]);
                break;
            case 1:
                form.change('status', status[2]);
                break;
            default:
        }
        handleSubmitWithRedirect('list');
    }, [form]);

    return <SaveButton {...props} handleSubmitWithRedirect={handleClick} />;
};

// ------------------------------------------------------------------------------------------
export const MyToolbar= props => (
    <Toolbar {...props} >
        <SaveButton
            label="Speichern"
            redirect="list"
            submitOnEnter={true}
            variant="text"
        />

        <FormDataConsumer>
            {({ formData, ...rest }) =>
                <StatusButton
                    label="Statuswechsel"
                    redirect="list"
                    submitOnEnter={false}
                    variant="text"
                    formdata={formData}  
                />
            }
        </FormDataConsumer>
    </Toolbar>
);

Update: you can see an example in codesandbox:更新:您可以在 codeandbox 中看到一个示例:

https://codesandbox.io/s/react-admin-accessformdata-v0uq7?fontsize=14&hidenavigation=1&initialpath=%23%2Fposts%2F1%2Fshow&module=%2Fsrc%2Fposts%2FPostShow.js&theme=dark https://codesandbox.io/s/react-admin-accessformdata-v0uq7?fontsize=14&hidenavigation=1&initialpath=%23%2Fposts%2F1%2Fshow&module=%2Fsrc%2Fposts%2FPostShow.js&theme=dark

The field values of the current form can be read accessed this:可以通过以下方式读取当前表单的字段值:

import { useForm } from 'react-final-form';

const form = useForm();
var formdata = form.getState().values;

formdata contains the whole form values as an object. formdata包含整个表单值作为一个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM