【发布时间】:2021-09-17 15:32:40
【问题描述】:
我正在尝试键入要使用 i18next 翻译的对象数组,但以下消息出现在变量 navItems 中,我在其中声明 i18next 以然后迭代数组 Type 'NavItemProps[]' does not satisfy the constraint 'string | TemplateStringsArray'. Property 'raw' is missing in type 'NavItemProps[]' but required in type 'TemplateStringsArray'
在地图内属性“地图”message does not exist on type 'string | object | (string | object)[]'. Property 'map' does not exist on type 'string'
我将它用作通过此链接输入 i18next 的参考,但没有成功 i18next: Map an array of objects in TypeScript
组件
const DesktopNav = ({hasBackground}: DesktopNavProps) => {
const {t} = useTranslation('navbar')
const linkColor = useColorModeValue(
hasBackground ? 'black' : 'white',
'gray.200'
)
const linkHoverColor = useColorModeValue('gray.400', 'white')
const popoverContentBgColor = useColorModeValue('white', 'gray.800')
const navItems = t<NavItemProps[]>('menu', {returnObjects: true})
return (
<C.List display={'flex'} alignItems={'center'}>
{navItems?.map((item: NavItemProps, index: number) => (
<C.ListItem key={index}>
<C.Popover trigger={'hover'} placement={'bottom-start'}>
<C.PopoverTrigger>
<C.Link
p={3}
href={item.href ?? '#'}
fontWeight={500}
color={linkColor}
_hover={{
textDecoration: 'none',
color: linkHoverColor,
}}
>
{item.label}
</C.Link>
</C.PopoverTrigger>
</C.Popover>
</C.ListItem>
))}
</C.List>
)
}
界面
interface NavItemProps {
label: string
href?: string
subLabel?: string
children?: Array<NavItemProps>
}
Json 文件翻译
{
"menu": [
{
"label": "jobs",
"href": "/"
},
{
"label": "about",
"href": "/about"
},
{
"label": "Blog",
"href": "/blog"
},
{
"label": "contact",
"href": "/contact"
}
]
}
【问题讨论】:
-
您的
NavItemProps接口不应该是interface NavItemProps { label: string; href: string; }之类的吗?这是您的 JSON 中menu下项目的格式。 -
@juliomalves 不,我已经告诉你 href、sublabel 和 children 属性是可选的
标签: reactjs typescript next.js internationalization i18next