通过扩展排版,使用 Material UI 在 React 中进行 i18n 本地化?

i18n Localization in React with Material UI by extending Typography?

当我认为我可以使用 MaterialUI 的 Typography 组件(已经在我的app) 来隐藏逻辑。

➡️有recommendation/advice做不做的吗?

➡️ 这样好吗?

示例

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>
}

它并不适合所有用例(例如,对于使用挂钩的按钮文本),但这是我使用的:

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属性,直接把key作为children。