# gt-react: General Translation React SDK: msg URL: https://generaltranslation.com/zh/docs/react/api/strings/msg.mdx --- title: msg description: msg() 字符串函数 API 参考 --- {/* 自动生成:请勿直接修改。请改为在 content/docs-templates/ 中编辑模板。 */} ## 概述 `msg` 函数用于标记并编码可翻译内容。 ```jsx const encodedString = msg('Hello, world!'); ``` 编码后的字符串应传给 [`useMessages`](/docs/react/api/strings/use-messages) Hook,以获取译文。 **编码:** `msg` 会对输入字符串进行编码,因此你不能在 JSX 或其他位置直接使用它。 如果你想取回原始字符串,需要使用 [`decodeMsg`](#decodemsg) 对其进行解码。 ## 解码 [#decodemsg] 要恢复原始字符串,需要使用 [`decodeMsg`](#decodemsg) 对其进行解码 ```jsx import { msg, decodeMsg } from 'gt-react'; const encodedString = msg('Hello, world!'); const decodedString = decodeMsg(encodedString); console.log(decodedString); // "Hello, world!" ``` ## 参考 ### 参数 | Name | Type | Description | | ---------- | ------------------------------------------------------------------------------ | -------------------- | | `content` | `string` | 要编码的文本内容。 | | `options?` | [`InlineTranslationOptions`](/docs/react/api/types/inline-translation-options) | 用于自定义 `msg` 行为的翻译选项。 | ### 返回值 一个编码后的字符串,其中的插值变量 (如有) 会替换为其对应的值。 *** ## 行为 ### 生产环境 在 CD 过程中,`msg` 函数中的任何内容都会在应用部署前完成翻译。 这样可以确保所有区域设置都有较快的加载速度,但它只能翻译在构建时已知的内容。 翻译生成后,会根据你的配置:(1) 存储在 CDN 中,或 (2) 存储在应用的构建输出中。 之后,这些翻译内容会提供给用户。 如果未找到翻译,则会回退到原始内容。 请务必遵循[此处的部署指南](/docs/react/tutorials/quickdeploy)。 ### 开发 在开发过程中,`msg` 函数会按需翻译内容。 这对于原型验证很有帮助,方便你查看应用在不同语言下的显示效果。 请记得在环境变量中添加 Dev API key,以启用此行为。 在开发环境中按需翻译时,你会注意到一定的延迟。 除非内容被明确设置为按需翻译,否则生产构建中不会出现这种情况。 *** ## 示例 ### 基本用法 你可以使用 `msg` 将字符串标记为待翻译内容。 ```jsx copy import { msg, useMessages } from 'gt-react'; const encodedString = msg('Hello, world!'); export default function TranslateGreeting() { const m = useMessages(); return (

{m(encodedString)}

); } ``` 注意:"Hello, world!" 会被翻译成用户偏好的语言。 ### 使用变量 [#variables] 你可以在字典翻译中传入变量。 ```jsx copy import { msg, useMessages } from 'gt-react'; const encodedString = msg('Hello, {name}!', { name: 'Alice' }); export default function TranslateGreeting() { const m = useMessages(); return (

{m(encodedString)}

); } ``` 注意:"Alice" 不会被翻译成用户的首选语言,因为它是变量。 ### 使用 ICU 消息格式 `gt-react` 支持 ICU 消息格式,因此你也可以对变量进行格式化。 ```jsx copy import { msg, useMessages } from 'gt-react'; const encodedString = msg('There are {count, plural, =0 {no items} =1 {one item} other {{count} items}} in the cart', { count: 10 }); export default function TranslateGreeting() { const m = useMessages(); return (

{m(encodedString)}

); } ``` ICU 消息格式是一种功能强大的变量格式化方式。 更多信息,请参阅 [ICU 消息格式文档](https://unicode-org.github.io/icu/userguide/format_parse/messages/)。 *** ## 说明 * `msg` 函数用于将字符串标记为待翻译内容。 * 使用 `msg` 的字符串会在 runtime 之前、也就是构建过程中完成翻译 (开发环境除外) 。 ## 后续步骤 * 要翻译字符串,请参阅 [`useMessages`](/docs/react/api/strings/use-messages)。