Reactjs 如何传入使用;这个“那个”另一件事;语法?
我有下面的mapper函数,其中我试图在JSX属性中指定一个值,但是类型定义不允许我传入该值。下面是代码Reactjs 如何传入使用;这个“那个”另一件事;语法?,reactjs,typescript,jsx,Reactjs,Typescript,Jsx,我有下面的mapper函数,其中我试图在JSX属性中指定一个值,但是类型定义不允许我传入该值。下面是代码 function mapper(notification: NotificationMessageType) { let style = "info"; switch (notification.icon) { case NotificationIconEnum.Error: style = "error";
function mapper(notification: NotificationMessageType) {
let style = "info";
switch (notification.icon) {
case NotificationIconEnum.Error:
style = "error";
break;
case NotificationIconEnum.Warning:
style = "warning";
break;
}
return (
<Notification
key={notification.id}
type={{ style: style }}
closable={true}
onClose={() => notificationContext.close(notification.id)}>
<span>{notification.message}</span>
</Notification>
);
}
但是我在那里传入一个字符串
,会导致TypeScript说它不是兼容的类型
由于无法从通知导入该类型定义,如何传入该值
编辑:
顺便说一下,错误消息说
类型“string”不可分配给类型“info”|“error”|“warning”
|“无”|“成功”。ts(2322)通知。d.ts(57,9):预期
类型来自属性“style”,该属性在类型“”上声明{
样式?:“信息”|“错误”|“警告”|“无”|“成功”图标?:
布尔;}'
虽然您可以将样式
变量定义为具有该类型:
let style: 'error' | 'warning' | 'info' = 'info';
将其放入函数中会更干净,并避免使用开关作为奖励:
const getStyle = (icon: NotificationIconEnum) => {
if (icon === NotificationIconEnum.Error) return 'error';
if (icon === NotificationIconEnum.Warning) return 'warning';
return 'info';
};
function mapper(notification: NotificationMessageType) {
return (
<Notification
key={notification.id}
type={{ style: getStyle(notification.icon) }}
closable={true}
onClose={() => notificationContext.close(notification.id)}>
<span>{notification.message}</span>
</Notification>
);
}
const getStyle=(图标:NotificationIconEnum)=>{
if(icon==NotificationIconEnum.Error)返回“Error”;
if(icon==NotificationIconEnum.Warning)返回“Warning”;
返回“信息”;
};
函数映射器(通知:NotificationMessageType){
返回(
notificationContext.close(notification.id)}>
{notification.message}
);
}
这样TS就可以自动推断出正确的所需类型,而不会产生额外的类型噪音。啊,你说得对。这似乎让TS满意。谢谢
const getStyle = (icon: NotificationIconEnum) => {
if (icon === NotificationIconEnum.Error) return 'error';
if (icon === NotificationIconEnum.Warning) return 'warning';
return 'info';
};
function mapper(notification: NotificationMessageType) {
return (
<Notification
key={notification.id}
type={{ style: getStyle(notification.icon) }}
closable={true}
onClose={() => notificationContext.close(notification.id)}>
<span>{notification.message}</span>
</Notification>
);
}