用于 @wordpress/i18n 的 React 绑定。

安装

安装该模块:

npm install @wordpress/react-i18n

此包假定你的代码将在 ES2015+ 环境中运行。如果你使用的环境对此类语言特性和 API 的支持有限或完全不支持,则应在你的代码中包含 @wordpress/babel-preset-default 中附带的 polyfill。

API

I18nProvider

I18nProvider 应挂载在任何本地化组件的上层:

用法

import { createI18n } from '@wordpress/i18n';
import { I18nProvider } from '@wordpress/react-i18n';
const i18n = createI18n();

ReactDom.render(
    <I18nProvider i18n={ i18n }>
        <App />
    </I18nProvider>,
    el
);

你也可以在未传入 i18n 属性的情况下实例化该 Provider。在这种情况下,它将使用
从 @wordpress/i18n 导出的默认 I18n 实例。

参数

  • props I18nProviderProps:i18n Provider 属性。

返回值

  • 包裹在 I18nProvider 中的子元素。

useI18n

提供 i18n 函数访问能力的 React hook。它公开了来自 @wordpress/i18n 的 __、_x、_n、_nx、isRTL 和 hasTranslation 函数。请参阅相应文档。

用法

import { useI18n } from '@wordpress/react-i18n';

function MyComponent() {
    const { __ } = useI18n();
    return __( 'Hello, world!' );
}

withI18n

React 高阶组件,可作为 props 将 i18n 翻译函数(与 useI18n hook 公开的函数集合相同)传递给被包裹的组件。

用法

import { withI18n } from '@wordpress/react-i18n';

function MyComponent( { __ } ) {
    return __( 'Hello, world!' );
}

export default withI18n( MyComponent );

参数

  • InnerComponent ComponentType< P >:要被包裹并接收 __ 等 i18n 函数的 React 组件

返回值

  • FunctionComponent< PropsAndI18n< P > >:被包裹的组件

为此包做贡献

这是属于 Gutenberg 项目的独立包。该项目以 monorepo 形式组织,由多个自包含的软件包组成,每个包都有特定用途。这个 monorepo 中的包会发布到 npm,并被 WordPress 及其他软件项目使用。

要了解更多关于为此包或整个 Gutenberg 做贡献的信息,请阅读项目的主要 贡献者指南。