在react组件外部使用next-intl

kknvjkwl  于 2023-04-30  发布在  React
关注(0)|答案(1)|浏览(129)

有没有办法在react组件之外使用next-intl
现在我通过调用钩子useTranslations来获取t,然后将其示例传递给我的函数:

function formatFoo(t, foo) {
    if ....
        t('bar');
}

export default function MyComponent() { 
    const t = useTranslations();
    return <div>{formatFoo(t, "bar")}</div>
}

例如,我希望我可以从next-intl导入t,因为i18next允许。

vql8enpb

vql8enpb1#

直接在组件体中调用formatFoo并从外部闭包使用t是否有问题?

export default function MyComponent() { 
  const t = useTranslations();

  function formatFoo(foo) {
    if ....
      return t('bar');
  }

  return <div>{formatFoo('bar')}</div>
}

next-intl只提供了一个API来使用React组件中的翻译。
这似乎是一个不必要的限制,但这是故意的,旨在鼓励使用经过验证的模式,以避免潜在的问题,如格式化的消息与应用程序状态不同步。
我写了一篇博客文章,讨论了这个设计决策的背景:How (not) to use translations outside of React components
注意:我是next-intl的维护者。

相关问题