我知道 react-i18next 在每个组件中都可以工作:函数式(使用 useTranslation)和类组件(使用 withTranslation())但是我不能在这样的基本函数中使用翻译:
const not_a_component = () => {
const { t } = useTranslation();
return t('translation')
};
const translate = not_a_component();
Run Code Online (Sandbox Code Playgroud)
错误钩子!
谢谢 !
您可以使用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;
Run Code Online (Sandbox Code Playgroud)
如果您选择仅使用,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');
});
Run Code Online (Sandbox Code Playgroud)
希望有帮助!!!
或者,您可以t
作为附加参数传递:
const not_a_component = (t) => {
return t('translation')
};
// Within a component
const { t } = useTranslation()
not_a_component(t)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1209 次 |
最近记录: |