React admin用typescript编辑缺少标题的记录



为了在react admin下使用Typescript功能,我按照这个官方示例键入了编辑标题:

interface UserTitleProps {
record: UserRecord;
}
const UserTitle: FC<UserTitleProps> = ({ record }) => {
const identifier = record?.email || record?.phoneNumber;
if (record?.name) {
return `${record?.name} (${identifier})`;
}
return identifier;
};
export const UserEdit: FC<EditProps> = (props) => (
<Edit
title={<UserTitle />}
{...props}
>
<UserForm />
</Edit>
);

但上面的代码给了我以下打字错误:

Property 'record' is missing in type '{}' but required in type 'UserTitleProps'.  TS2741
103 | export const UserEdit: FC<EditProps> = (props) => (
104 |   <Edit
> 105 |     title={<UserTitle />}
|             ^
106 |     {...props}
107 |   >
108 |     <UserForm />

事实上,record道具并没有真正传递,但根据文档和下面的示例,没有什么可添加的。

我是不是错过了什么?

感谢

如果你仔细检查了这个:

interface UserTitleProps {
record?: UserRecord; // make this an optional property
}

您会注意到record是一个可选属性,但在您的代码中它是强制性的
因此,对于您的案例,您需要传递record道具。

但是,如果您更新该行,使prop成为可选的,那么TypeScript应该停止抱怨,除非另有说明。


从他们的页面标题文档

React管理员表示,当您将元素作为title传递时,它将被克隆
<EditView>中,将当前记录注入title

因此,您永远不必显式传递record道具
因此CCD_ 9应该总是一个";可选的";prop添加到接口时,因为您永远不必直接传递它。

在这个视频中,你可以看到下面发生了什么,以防你对细节感兴趣。

export const UserEdit: FC<EditProps> = (props) => {
return (
<Edit
title={<UserTitle />} // "record" prop is never passed explicitly
{...props}
>
<UserForm />
</Edit>
);
};

这段代码帮助我处理了这个问题。我的代码示例有效:

const EditTitle = ( record : any ) => {
return <span>Change feed state of {record.record ? `${record.record.feed}` : ''}</span>;
};

在调试打印之后,我意识到记录实际上是一个对象,并且包含带有我需要的字段的记录属性。我也使用TS。

相关内容

最新更新