【问题标题】:i18n Localization in React with Material UI by extending Typography?通过扩展 Typography 在 React 中使用 Material UI 进行 i18n 本地化?
【发布时间】:2020-05-05 04:35:12
【问题描述】:
当我认为我可以使用 MaterialUI 的 Typography 组件(已经在我的应用程序中)隐藏逻辑时,我开始了将 react-i18next 的 useTranslation 钩子添加到我的所有组件的痛苦工作。
➡️ 有什么建议/建议做或不做吗?
➡️这是个好主意吗?
例子
import React from 'react'
import {useTranslation} from 'react-i18next'
import { Typography } from '@material-ui/core'
const TranslatedTypography = ({children}) => {
const {t} = useTranslation()
return <Typography>{t(children)}</Typography>
}
【问题讨论】:
标签:
reactjs
localization
internationalization
material-ui
i18next
【解决方案1】:
它并不适合所有用例(例如,对于使用挂钩的按钮文本),但这是我使用过的:
import { Trans } from 'react-i18next'
import { Typography } from '@material-ui/core'
import React from 'react'
const TranslatedTypography = ({
children,
i18nKey,
count = 1,
...otherProps
}) => {
return (
<Typography {...otherProps}>
<Trans i18nKey={i18nKey} count={count}>
{children}
</Trans>
</Typography>
)
}
export default TranslatedTypography
你可以按如下方式使用它:
<TranslatedTypography
i18nKey="yourKey"
variant="h6">
title
</TranslatedTypography>
注意:看来你也可以省略i18nKey 属性,直接把钥匙当作孩子。