react中 react-i18next 在转换文字时如何不使用hooks调用
时间: 2023-09-14 20:09:57 浏览: 53
类似于 react-intl,react-i18next 也提供了在类组件中使用的 API,可以不使用 hooks 实现国际化。其中比较常用的是 withTranslation HOC 和 Translation 组件。
withTranslation HOC 可以注入 t 函数到组件的 props 中,从而在组件中获取对应的国际化文本。示例代码如下:
```
import React from 'react';
import { withTranslation } from 'react-i18next';
class MyComponent extends React.Component {
render() {
const { t } = this.props;
return <div>{t('myMessageId')}</div>;
}
}
export default withTranslation()(MyComponent);
```
在这个示例中,通过 withTranslation HOC 注入了 t 函数到组件的 props 中,然后在 render 方法中使用该函数来获取对应的国际化文本。
Translation 组件可以用于在 JSX 中显示国际化文本,类似于 FormattedMessage 组件。它接受一个 i18nKey 属性和一个 fallback 属性,分别表示需要翻译的文本的键和默认文本。示例代码如下:
```
import React from 'react';
import { Translation } from 'react-i18next';
class MyComponent extends React.Component {
render() {
return (
<div>
<Translation i18nKey="myMessageId" fallback="Hello, World!" />
</div>
);
}
}
export default MyComponent;
```
在这个示例中,使用 Translation 组件来显示国际化文本,传入了 i18nKey 属性和 fallback 属性,分别对应需要翻译的文本的键和默认文本。