我在react-admin
应用程序中为ReferenceField
创建了一个简单的包装器组件:
import {FC} from "react";
import {ReferenceField, ReferenceFieldProps} from "react-admin";
export const UserReference: FC<Omit<ReferenceFieldProps, "reference" | "label">> = (props) => {
return <ReferenceField {...props} label="User" reference="users" />;
};
UserReference.displayName = "UserReference";
但是当使用字段时,标签仍然是从source
属性推断出来的(这是默认的)。当我直接使用带有标签的ReferenceField
时,它可以工作:
// UserReference renders label "User id" and ReferenceField renders correct "User"
<Datagrid>
<UserReference source="user.id" />
<ReferenceField reference="users" label="User" source="user.id" />
</Datagrid>
为什么会发生这种情况,我该如何修复它?我是否需要转发裁判?
<Datagrid>
检查它的子标签prop来构建标题行。因此,为了使它在你的情况下工作,你必须在defaultProps
:
import {FC} from "react";
import {ReferenceField, ReferenceFieldProps} from "react-admin";
export const UserReference: FC<Omit<ReferenceFieldProps, "reference" | "label">> = (props) => {
return <ReferenceField {...props} reference="users" />;
};
UserReference.displayName = "UserReference";
UserReference.defaultProps = { label: 'User' };
这在react-admin文档中有记录:https://marmelab.com/react-admin/Fields.html#writing-your-own-field-component