Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

using the t() from react-i18next outside of a component

I am using i18next and react-i18next in a react native application, more specifically with input validation. I am trying to pass the t() as a parameter in a no component and i am receiving the error "TypeError: n is not a function. (In 'n('errorMessages.emailNoMatch')', 'n' is undefined)". any suggestions is highly appreciated since I am relatively new to coding and I have been searching for a couple days with this issue.

here is the i18n.js code:

import i18next from 'i18next';
import common_de from './translations/de/common.json';
import common_en from './translations/en/common.json';
import i18n from 'i18n-js';
import * as Localization from 'expo-localization';
// Set up translations
i18next.init({
  interpolation: { escapeValue: false }, // React already does escaping
  lng: 'en', // language to use
  resources: {
    de: {
      common: common_de, // 'common' is our custom namespace
    },
    en: {
      common: common_en,
    },
  },
  debug: true,
});
export default i18next;

a part of the RegisterValidator.js code where I am trying to pass the t() as a parameter, but it is not reading t as a parameter inside of the switch statement.:

import React from 'react';
import { useTranslation } from 'react-i18next';
// import { withTranslation } from 'react-i18next';

const RegisterValidator = (type, value, email, t) => {
  let validated = true;
  let warningMsg = [];
  switch (type) {
    case 'username':
      if (!value.includes(' ')) return [true, ''];
      else {
        warningMsg = t('errorMessages.username');
        return [false, warningMsg];
      }
    default:
      return [validated, ''];
  }
};
export default RegisterValidator;

and here is a part from the App.js

import React from 'react';
import './i18n';
import i18n from 'i18n-js';
import i18next from 'i18next';
import { I18nextProvider } from 'react-i18next';

function App() {
  return (
    <I18nextProvider i18n={i18next}>
      <Insert more code here />
    </I18nextProvider>
  );
}

export default App;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

t() outside component won't work, instead send a message object to RegisterValidator and use that. Example -

function Component() {
// t is declared here
const message = {
error: t('errorMessage'),
success: t('successMessage')
}

// and then send this message object to RegisterValidator

RegisterValidator(.., .., .., message);

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...