--- createdAt: 2024-03-07 updatedAt: 2025-09-30 title: 在 React 和 Next.js 中制作多语言(i18n)组件 description: 学习如何声明和获取本地化内容,以使用 Intlayer 构建多语言 React 或 Next.js 组件。 keywords: - i18n - 组件 - react - 多语言 - next.js - intlayer slugs: - doc - component - i18n applicationTemplate: https://github.com/aymericzip/intlayer-vite-react-template youtubeVideo: https://www.youtube.com/watch?v=dS9L7uJeak4 --- # 如何使用 Intlayer 制作多语言(i18n)组件 本指南展示了在两种常见环境中制作多语言 UI 组件的最简步骤: - React(Vite/单页应用) - Next.js(应用路由) 您将首先声明内容,然后在组件中获取内容。 ## 1) 声明您的内容(适用于 React 和 Next.js) 在组件附近创建一个内容声明文件。这可以让翻译内容靠近使用位置,并且支持类型安全。 ```ts fileName="component.content.ts" import { t, type Dictionary } from "intlayer"; const componentContent = { key: "component-example", content: { title: t({ en: "Hello", fr: "Bonjour", es: "Hola", }), description: t({ en: "A multilingual React component", fr: "Un composant React multilingue", es: "Un componente React multilingüe", }), }, } satisfies Dictionary; export default componentContent; ``` 如果您更喜欢配置文件,也支持 JSON 格式。 ```json fileName="component.content.json" { "$schema": "https://intlayer.org/schema.json", "key": "component-example", "content": { "title": { "nodeType": "translation", "translation": { "en": "Hello", "fr": "Bonjour", "es": "Hola" } }, "description": { "nodeType": "translation", "translation": { "en": "一个多语言的 React 组件", "fr": "Un composant React multilingue", "es": "Un componente React multilingüe" } } } } ``` ## 2) 获取您的内容 ### 情况 A — React 应用 (Vite/SPA) 默认方法:使用 `useIntlayer` 通过键来获取内容。这使组件保持简洁且类型安全。 ```tsx fileName="ComponentExample.tsx" import { useIntlayer } from "react-intlayer"; export function ComponentExample() { const content = useIntlayer("component-example"); return (
{content.description}
{content.description}
> ); } ``` 另一种方式:如果你更喜欢在调用处组织结构,可以使用 `useDictionary` 读取整个声明的对象。 ```tsx fileName="ComponentWithDictionary.tsx" import { useDictionary } from "react-intlayer"; import componentContent from "./component.content"; export function ComponentWithDictionary() { const { title, description } = useDictionary(componentContent); return ({description}
{content.description}
> ); } ``` ```tsx fileName="app/[locale]/example/ClientComponent.tsx" "use client"; import { useIntlayer } from "next-intlayer"; export function ClientComponent() { const content = useIntlayer("component-example"); return ({content.description}