如何在不使用 <SimpleForm> 的情况下访问编辑功能中的记录?

How to access record inside Edit function without having to use <SimpleForm>?

我有一个 <Ressource>App.tsx 中声明如下:

<Resource name="myresource" list={ListGuesser} edit={GenericEdit}/>

GenericEdit的代码:

const GenericEdit = function (props) {
    console.log('props', props);
    console.log('useResourceContext()', useResourceContext());
    console.log('useRecordContext()', useRecordContext());
    return (
        <>
            <Edit {...props}>
                <SimpleForm>
                    <TextInput disabled label="Id" source="id" />
                    <TextInput label="Name" source="name" />
                </SimpleForm>
            </Edit>
        </>)
};
export default GenericEdit;

<Edit><SimpleForm> 默认设置运行良好(即记录数据在表单内呈现),但是我希望能够使用 record 数据我自己的方式:


问:如何在我的编辑功能 (GenericEdit) 中访问记录数据,而不必依赖默认的 <SimpleForm> 功能?

您可以使用Edit和EditView组件的源码来实现您的表单显示。在源文中可以看到是Edit提供了记录数据的传递:Edit.tsx, EditView.tsx

export const Edit = ( props: EditProps & { children: ReactElement } ): ReactElement => {

    useCheckMinimumRequiredProps('Edit', ['children'], props);
    const controllerProps = useEditController(props);

    const body = (
        <EditContextProvider value={controllerProps}>       
            <EditView {...props} {...controllerProps} /> // Your component for displaying form            
        </EditContextProvider>
    );

    return props.resource ? (
        // support resource override via props
        <ResourceContextProvider value={props.resource}>
            {body}
        </ResourceContextProvider>
    ) : (
        body
    );
};         


   

来自 React 管理员支持的回答,对我有用

The Edit component fetches the data and passes it to its children. In order to access fetch data, you would have to add an intermediate component and use the useRecordContext hook.

const MyForm = props => {
    const record = useRecordContext(props);
    console.log({ record });
    return (
        <>
            {/* We can still use the built-in React Admin */}
            <SimpleForm {...props}>
                <TextInput source="id" />
            </SimpleForm>
            {/* Or use something custom */}
            <div>{JSON.stringify(record)}</div>
        </>
    );
};

const GenericEdit = props => (
    // Here, the data hasn't been fetched yet 
    <Edit {...props} >
        <MyForm />
    </Edit>
);
export default GenericEdit;