我知道 react-i18next 在每个组件中都有效:功能(使用 useTranslation)和类组件(使用 withTranslation())但是我不能在这样的基本函数中使用翻译:
const not_a_component = () => {
const { t } = useTranslation();
return t('translation')
};
const translate = not_a_component();
错误挂钩!
谢谢 !
我知道 react-i18next 在每个组件中都有效:功能(使用 useTranslation)和类组件(使用 withTranslation())但是我不能在这样的基本函数中使用翻译:
const not_a_component = () => {
const { t } = useTranslation();
return t('translation')
};
const translate = not_a_component();
错误挂钩!
谢谢 !
您可以使用i18next
库来使用 javascript 进行翻译。
react-i18next
只是i18next
.
下面是一个示例,如果您已经在使用react-i18next
并且已配置。
import i18next from "i18next";
const not_a_component = () => {
const result = i18next.t("key");
console.log(result);
return result;
};
export default not_a_component;
如果您选择仅使用,i18next
那么您可以简单地获得t
功能。这一切都取决于您的要求。
import i18next from 'i18next';
i18next.init({
lng: 'en',
debug: true,
resources: {
en: {
translation: {
"key": "hello world"
}
}
}
}, function(err, t) {
// You get the `t` function here.
document.getElementById('output').innerHTML = i18next.t('key');
});
希望有帮助!!!
t
或者,您可以作为附加参数传递:
const not_a_component = (t) => {
return t('translation')
};
// Within a component
const { t } = useTranslation()
not_a_component(t)