# General Translation React SDKs (gt-react, gt-next, gt-react-native): useMessages
URL: https://generaltranslation.com/zh/docs/react/reference/hooks/use-messages.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: useMessages 的 API 参考。将通过 msg 注册的字符串解析为当前区域设置。

`useMessages` 钩子会返回一个函数，用于将通过 [`msg`](/docs/react/reference/functions/msg) 创建的编码后的字符串解析为当前区域设置。可用它来翻译在模块层级 (组件外) 注册的字符串。

*可用于 `gt-react`、`gt-next`、`gt-tanstack-start` 和 `gt-react-native`。*

## 概览 [#overview]

先用 [`msg`](/docs/react/reference/functions/msg) 注册一个字符串，再用 `useMessages` 返回的函数将其解析。

```tsx
const m = useMessages();

<p>{m(encodedString)}</p>;
```

*注：在 `gt-react` 中，请在 [`<GTProvider>`](/docs/react/reference/components/gt-provider) 内调用 `useMessages`。在 `gt-next` 中，它也可用于同步的服务器组件。*

## 工作原理 [#how-it-works]

* **解析已注册的字符串。** 它会查找先前由 [`msg`](/docs/react/reference/functions/msg) 编码后的字符串对应的翻译，并以当前区域设置返回。
* **透传。** `null` 和 `undefined` 会原样返回。
* **变量优先级。** 当变量同时传给 [`msg`](/docs/react/reference/functions/msg) 和解析器时，传给 [`msg`](/docs/react/reference/functions/msg) 的值优先。
* **构建时翻译。** 与 [`useGT`](/docs/react/reference/hooks/use-gt) 一样，翻译会在构建时进行 (或在开发期间按需进行) ，变量则永远不会被翻译。

## 参数 [#parameters]

`useMessages` 无需传入参数。

## 返回值 [#returns]

**类型** `(encodedContent: string, options?: object) => string`

一个函数，用于将 [`msg`](/docs/react/reference/functions/msg) 中的编码内容解析为当前区域设置。

| Name             | Description                                                | Type     | Optional |
| ---------------- | ---------------------------------------------------------- | -------- | -------- |
| `encodedContent` | 要解析的 [`msg`](/docs/react/reference/functions/msg) 编码后的字符串。 | `string` | 否        |
| `options`        | 传递给编码字符串的插值变量。                                             | `object` | 是        |

## 示例 [#examples]

*示例从 `gt-react` 导入；请改为从所用框架的 package 导入。*

```tsx
import { msg, useMessages } from 'gt-react';

const encodedGreeting = msg('Hello, Alice!');

export default function TranslateGreeting() {
  const m = useMessages();
  return <p>{m(encodedGreeting)}</p>;
}
```

```tsx
import { msg, useMessages } from 'gt-react';

const encodedGreeting = msg('Hello, {name}!');

export default function TranslateGreeting() {
  const m = useMessages();
  return <p>{m(encodedGreeting, { name: 'Bob' })}</p>; // "Hello, Bob!"
}
```

```tsx
import { msg, useMessages } from 'gt-react';

// 传递给 msg() 的变量优先级高于传递给 m() 的变量
const encodedGreeting = msg('Hello, {name}!', { name: 'Alice' });

export default function TranslateGreeting() {
  const m = useMessages();
  return <p>{m(encodedGreeting, { name: 'Bob' })}</p>; // "Hello, Alice!"
}
```

## 注意事项 [#notes]

* `useMessages` 会解析来自 [`msg`](/docs/react/reference/functions/msg) 的编码后的字符串。
* 在异步 App Router 组件中，请改用 [`getMessages`](/docs/react/nextjs/reference/functions/get-messages)。
* 翻译会在构建时进行 (开发环境中则按需进行) 。

## Sitemap

See the full [sitemap](https://generaltranslation.com/sitemap.md) for all pages.
