如何提取 useTranslate 作为辅助函数而不是组件?

How to extract useTranslate as a helper function but not a component?

我现在正在使用 Next.js,我正在尝试使用 'next-translate/useTranslation'

对这些文本进行翻译

因为我可能没有翻译应用程序中的所有字符串,所以我编写了一个检查函数来检查字符串是否在我的翻译 JSON 文件中(常见)。如果是,return 翻译后的字符串,否则只显示原始字符串

目标是将翻译检查功能提取为实用功能,可以在每个页面中重复使用。

当前用法:将函数复制到每个需要翻译的组件中(因此在每个组件中重复代码)

type Props = {}

const testComponent: FunctionComponent<Props> = () => {
  const { t, lang } = useTranslation('common');

  //the checking function used
  const checkStringTranslated = (string2bChecked:string)=>{
    if(t(string2bChecked).includes('common'))return false
    return true
  }
  
  return (
    <div>
      <p>{checkStringTranslated("String2bTranslated")?t("String2bTranslated"):"String2bTranslated"}</p>
    </div>
  )
}

我找到了一个 post 可以做到这一点,但在 Next.js 中找不到:

而且我不知道如何在 Next.js 中做到这一点。我怎样才能减少它的冗余?

您不需要为其创建辅助函数,next-translate 在调用 t 函数来自 useTranslate.

const testComponent: FunctionComponent<Props> = () => {
    const { t } = useTranslation('common');
  
    return (
        <div>
            <p>{t("String2bTranslated", undefined, { default: "String2bTranslated" })}</p>
        </div>
    );
};