标签: react-i18next

如何通过 i18next 从 hoc 翻译的组件中检索 ref

我使用 i18next 在单独的 repo 中翻译我的组件。现在我需要使用主项目中一个组件的方法。这是示例组件:

class ExampleComponent extends React.Component {
  constructor(props) {
    this.state = {
      text: '',
    };
    this.resetText = this.resetText.bind(this);
  }

  resetText() {
    this.setState({
    text: '',
    });
  }

  render() {
    <div/>
  }

export default translate('components', { withRef: true })(ExampleComponent);
Run Code Online (Sandbox Code Playgroud)

现在我需要在我的主项目中使用 resetText,没有翻译它工作正常

class MainComponent extends Component {

  resetComponent() {
    return () => this.exampleComponent.resetText();
  }

  renderExampleComponent() {
    return (
      <ExampleComponent
        ref={(exampleComponent) => { this.exampleComponent = exampleComponent; }}
      />
    );
  }

  render() {
    return (
      <div>
        {this.resetComponent()}
      </div>
    );
  }
Run Code Online (Sandbox Code Playgroud)

我试过 this.refs.exampleComponent.resetText(); …

javascript i18next reactjs react-i18next

4
推荐指数
1
解决办法
441
查看次数

使用 Jest 测试 i18next 时如何修复“TypeError:无法读取未定义的属性“类型”

我有一个 react 项目,并且包含了 i18next = 15.0.4 和 react-i18next = 10.2.0 依赖项。我已经创建了一个用于使用 react-i18next 初始化 i18next 的模块,并且我正在尝试使用 Jest 对这段代码进行单元测试。

我尝试导入初始化 i18next 的 i18n 模块并使用 jest 对其进行单元测试。

这是我的 i18n.ts 模块

import i18next from "i18next";
import { initReactI18next } from "react-i18next";

const config = {
    resources: {
        en: {
            static: {},
        },
    },
    fallbackLng: "en",
    defaultNS: "static",
    ns: "static",
    interpolation: {
        prefix: "[",
        suffix: "]",
    },
};

i18next.use(initReactI18next).init(config);

export default i18next;
Run Code Online (Sandbox Code Playgroud)

我试图从我的测试代码中调用它(i18n.test.ts):

import i18n from "./i18n";

describe("i18n", () => {

    it("should work fine", () …
Run Code Online (Sandbox Code Playgroud)

typescript i18next jestjs react-i18next

4
推荐指数
2
解决办法
8070
查看次数

i18n.changeLanguage 不是函数

这是我的代码。

import React, { Suspense } from 'react';
import { useTranslation } from 'react-i18next';

function Page() {
  const { t, i18n } = useTranslation();

  const changeLanguage = lng => {
    i18n.changeLanguage(lng);
  };

  return (
    <div className="App">
      <div className="App-header">
        <button onClick={() => changeLanguage('de')}>de</button>
        <button onClick={() => changeLanguage('en')}>en</button>
      </div>
      <div>{t('test')}</div>
    </div>
  );
}

export default function App() {
  return (
    <Suspense fallback={<div>loading...</div>}>
      <Page />
    </Suspense>
  );
}
Run Code Online (Sandbox Code Playgroud)

当我点击de en按钮时。我收到这个错误。TypeError: i18n.changeLanguage is not a function.How to fix?

javascript typescript reactjs react-i18next

4
推荐指数
3
解决办法
8407
查看次数

How to fix 'no fallback UI was specified' in react i18next using hooks

I am trying to implement i18next in my react component using the useTranslation hook, but it keeps saying:

Uncaught Error: Test suspended while rendering, but no fallback UI was specified.

Add a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display.

我怎样才能添加<Suspense>比我拥有的更高的任何东西?我究竟做错了什么?我该如何解决?当我使用该<Translation>组件时,它似乎工作正常。当然,如果我关闭 Suspense 并尝试自己处理它似乎也可以正常工作,但我认为这违背了目的。我怎样才能使它真正起作用?我的 Fetch 后端是否配置错误?

测试.js

import React, { Suspense, useState, useEffect, lazy } from "react";
import PropTypes from "prop-types";

import i18n from './i18n';
import { useTranslation } …
Run Code Online (Sandbox Code Playgroud)

reactjs react-i18next react-hooks react-suspense

4
推荐指数
2
解决办法
1万
查看次数

如何正确模拟 i18next

这是我的函数和测试的简化版本。虽然我嘲笑了 useTranslation 我收到以下错误:

您正在传递一个未定义的模块!请检查您传递给 i18next.use() 的对象

   7 | i18n
   8 |   .use(Backend)
>  9 |   .use(initReactI18next)
Run Code Online (Sandbox Code Playgroud)

我如何正确模拟以消除此错误?

import React from 'react'
import { useTranslation } from 'react-i18next'
import * as Constants from 'constants'
import MyComponent from 'components'

const Dashboard = () => {
  const { t } = useTranslation('dashboard')
  return (
     <div> Dashboard 
      <MyComponent name={t(Constants.MYCOMPONENT)}/>
    </div>
  )
}

export default Dashboard
Run Code Online (Sandbox Code Playgroud)
jest.mock('react-i18next', () => ({
  useTranslation: () => ({ t: (key) => key })
}))
it('Render Dashboard without crash', () …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs enzyme react-i18next

4
推荐指数
1
解决办法
2774
查看次数

React Native 上的react-i18next 没有重载与此调用打字稿匹配

我正在尝试使用 typescript 4.1.2 在我的 React Native 应用程序中配置react-i18next 11.8.2:

i18n.use(initReactI18next).init({
  resources: {
    en,
    es,
  },
  lng: 'es',
  fallbackLng: 'es',
  interpolation: {
    escapeValue: false,
  },
});
Run Code Online (Sandbox Code Playgroud)

有两个资源文件(en,es)。

但我在使用 useTranslation 挂钩的 TFunction 接口中遇到打字稿错误:

const {t, i18n} = useTranslation(['SelectLanguage']);]

<StyledLabel>{t('SelectLanguage:title')}</StyledLabel>
Run Code Online (Sandbox Code Playgroud)

错误:

No overload matches this call.
  Overload 1 of 2, '(props: Pick<Pick<TextProps & RefAttributes<Text>, "key" | "ref" | "style" | "onLayout" | "testID" | "nativeID" | "accessible" | "accessibilityActions" | ... 35 more ... | "dataDetectorType"> & Partial<...>, "key" | ... 42 more ... …
Run Code Online (Sandbox Code Playgroud)

internationalization typescript react-native react-i18next react-native-ui-kitten

4
推荐指数
1
解决办法
6972
查看次数

React i18n - “t”函数不接受字符串变量(打字稿)?“没有与此调用匹配的过载”

任何熟悉此错误的人:[带有错误消息的代码][1] [1]:https://i.stack.imgur.com/SbJvu.png

{t(`${settingType}` as const)}
Run Code Online (Sandbox Code Playgroud)

错误:

No overload matches this call.
  Overload 1 of 2, '(key: TemplateStringsArray | Normalize<{
Run Code Online (Sandbox Code Playgroud)

谢谢 :)

typescript i18next react-i18next react-typescript

3
推荐指数
1
解决办法
3454
查看次数

React i18next languageChanged 事件被多次调用

我在我的 React js 应用程序中使用 i18next 进行翻译。我在 Header.jsx 文件中添加了所有页面通用的语言下拉列表。我正在我的页面quiz.jsx之一中根据当前语言获取数据。因此,在语言更改时应该再次调用 api。

问题解释

  1. i18Next 函数的languageChanged()事件在语言下拉列表更改时多次调用。它应该只被调用一次。我不知道为什么这个函数被多次调用?

  2. 我想仅在一个页面上实现i18Next 的languageChanged()事件,但目前它在每个页面上调用。所以 api 正在获取所有页面中的数据,这些数据对于该页面来说是不必要的数据。

i18Next 配置

语言.js

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import config from './config';
var resources = {};
//Dynamically reading languages from config file
config.supportedLanguages.forEach(element => {
  resources[element] = {
    translations: require('../locale/' + element + '.json')
  };
});
i18n.use(initReactI18next).init({
  fallbackLng: config.defaultLanguage,
  lng: config.defaultLanguage,
  resources,
  ns: ['translations'],
  defaultNS: 'translations',
  debug:true
});

i18n.languages = config.supportedLanguages;

export default i18n; …
Run Code Online (Sandbox Code Playgroud)

i18next reactjs react-i18next

3
推荐指数
1
解决办法
4466
查看次数

错误:您正在传递未定义的模块!请检查您传递给 i18next.use() 的对象

由于上述问题,我的单元测试失败了。

//String.ts
import * as i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import BrowserLanguageDetector from 'i18next-browser-languagedetector'
import Backend from 'i18next-http-backend'
import languageMap from '@katal/localization/webpack-loader!'

i18n
  .use(initReactI18next)
  .use(BrowserLanguageDetector)
  .use(Backend)
  .init({
    fallbackLng: 'en-US',
    load: 'currentOnly',
    detection: {
      order: ['sessionStorage', 'localStorage', 'querystring', 'navigator'],
      lookupQuerystring: 'locale',
      lookupLocalStorage: 'locale',
      lookupSessionStorage: 'locale',
      caches: [],
    },
    backend: {
      loadPath: (localeList: string[]) => languageMap[localeList[0]],
    },
    interpolation: {
      escapeValue: false,
    },
    react: {
      useSuspense: false,
    },
  })
Run Code Online (Sandbox Code Playgroud)

我嘲笑这一点的方式是:

const React = require('react')
const reactI18next = require('react-i18next')



module.exports …
Run Code Online (Sandbox Code Playgroud)

i18next react-i18next

3
推荐指数
1
解决办法
3352
查看次数

如何获取活动语言以外的翻译 React i18next

我有一个输入组件,用户应该用不同的语言输入文本。因此,当用户选择他想要使用的语言时,我希望将占位符翻译成不同的语言。我不想更改页面的活动语言。

有谁知道,如何手动从资源中获取翻译?

我没有使用任何工具来获取文本翻译。

我正在寻找类似的东西:

const [t, i18n] = useTranslation();
let translatedPlaceholder = t('Placeholder', 'de') // For translation to german 
Run Code Online (Sandbox Code Playgroud)

i18next reactjs react-i18next

3
推荐指数
1
解决办法
2194
查看次数