Creation:2024-08-11Last update:2025-06-29
将此文档参考到您的 AI 助手ChatGPTClaudeDeepSeekGoogle AI modeGeminiPerplexityMistralGrok
使用您最喜欢的AI助手总结文档,并引用此页面和AI提供商
此页面的内容已使用 AI 翻译。
查看英文原文的最新版本Edit this doc
If you have an idea for improving this documentation, please feel free to contribute by submitting a pull request on GitHub.
GitHub link to the documentationCopy
Copy doc Markdown to clipboard
React 集成:useI18n Hook 文档
本节详细介绍如何在 React 应用中使用 useI18n Hook,实现高效的内容本地化。
在 React 中导入 useI18n
可以根据不同的上下文,将 useI18n Hook 导入并集成到 React 应用中,具体如下:
客户端组件:
typescript复制代码复制代码到剪贴板
import { useI18n } from "react-intlayer"; // 在客户端 React 组件中使用服务器组件:
参数
此钩子接受两个参数:
namespace:用于限定翻译键的字典命名空间。locale(可选):期望使用的语言环境。如果未指定,则默认使用上下文的语言环境。
字典
所有字典键必须在内容声明文件中声明,以增强类型安全并防止错误。配置说明请参见此处。
React 中的使用示例
以下是在 React 组件中使用 useI18n 钩子的示例:
src/App.tsx
复制代码
复制代码到剪贴板
import type { FC } from "react";
import { ClientComponentExample, ServerComponentExample } from "@components";
import { IntlayerProvider } from "react-intlayer";
import { useI18n, IntlayerServerProvider } from "react-intlayer/server";
import { Locales } from "intlayer";
const App: FC<{ locale: Locales }> = ({ locale }) => {
const t = useI18n("home-page", locale);
return (
<>
<p>{t("introduction")}</p>
<IntlayerProvider locale={locale}>
<ClientComponentExample />
</IntlayerProvider>
<IntlayerServerProvider locale={locale}>
<ServerComponentExample />
</IntlayerServerProvider>
</>
);
};src/components/ComponentExample.tsx
复制代码
复制代码到剪贴板
import type { FC } from "react";
import { useI18n } from "react-intlayer";
const ComponentExample: FC = () => {
const t = useI18n("component-example");
return (
<div>
<h1>{t("title")}</h1> {/* 显示标题 */}
<p>{t("description")}</p> {/* 显示描述 */}
</div>
);
};src/components/ServerComponentExample.tsx
复制代码
复制代码到剪贴板
import { useI18n } from "react-intlayer/server";
const ServerComponentExample = () => {
const t = useI18n("server-component");
return (
<div>
<h1>{t("title")}</h1> {/* 显示标题 */}
<p>{t("description")}</p> {/* 显示描述 */}
</div>
);
};属性处理
在本地化属性时,请适当地访问翻译值:
html
复制代码
复制代码到剪贴板
<!-- 对于无障碍属性(例如 aria-label),请使用 .value,因为需要纯字符串 --><button aria-label={t("button.ariaLabel").value}>{t("button.text")}</button>额外资源
- Intlayer 可视化编辑器:为了获得更直观的内容管理体验,请参阅可视化编辑器文档 这里。
本节特别涵盖了在 React 应用中集成 useI18n 钩子,简化本地化流程并确保不同语言环境下内容的一致性。