# gt-react: General Translation React SDK: declareVar URL: https://generaltranslation.com/zh/docs/react/api/strings/declare-var.mdx --- title: declareVar description: declareVar() 字符串函数的 API 参考 --- {/* 自动生成:请勿直接修改。请改为修改 content/docs-templates/ 中的 template。 */} ## 概述 使用 `derive` 时,`declareVar` 函数相当于 `` 组件的字符串版本。 它用于在 `derive` 内容中标记动态内容;这些内容会被排除在哈希计算之外,并在 runtime 作为变量处理。 ```jsx function Component() { function getGreeting(name) { return "Hello, " + declareVar(name); } // 结果为:"Hello, {_gt_, select, other {Brian}}" gt(`${derive(getGreeting(name))}. How are you?`); // 结果为:"Hello, Brian. How are you?" return

{message}

; } ``` `declareVar` 会将动态内容包装为与 ICU 兼容的占位符,并在 runtime 时还原为原始值。 如果你想移除 ICU 标记,可以使用 [`decodeVars`](/docs/react/api/strings/decode-vars)。 **ICU 标记:** `declareVar` 会向源文本添加与 ICU 兼容的标记。如果后续字符串处理需要原始值,请使用 `decodeVars` 将其提取出来。 ## 参考 ### 参数 | 名称 | 类型 | 说明 | | --------------- | ----------------------------------------------------------- | --------------------------------------------- | | `value` | ` value \| string \| number \| boolean\| undefined \| null` | 要标记为变量的动态值。 | | `options?` | `Object` | `declareVar` 函数的选项。 | | `options.$name` | `string` | 变量名称,用于提供翻译上下文。 (类似于 `` 组件中的 `name` 属性) | ### 返回值 一个包含与 ICU 兼容标记的字符串,会保留原始值,并在 runtime 期间解析。 *** ## 行为 ### 变量标记 当 `declareVar` 包装一个值时,它会: 1. 将该值转换为 ICU `select` 语句格式 2. 将其标记为供翻译处理的动态内容 3. 在计算翻译哈希时将其排除 4. 保留原始值,以便在 runtime 进行插值 ### ICU 格式 该函数输出兼容 ICU MessageFormat 的字符串: ```jsx declareVar("John") // → "{_gt_, select, other {John}}" ``` *** ## 示例 ### 基本用法 在静态函数中为动态内容添加标记。 ```jsx copy import { derive, declareVar, gt } from 'gt-react'; function getGreeting(name) { return `Hello, ${declareVar(name)}!`; } function Component() { const name = "Brian"; const message = gt(`${derive(getGreeting(name))} Welcome back.`); return

{message}

; } ``` ### 与其他 ICU 函数结合使用 你可以将 `declareVar` 与其他 ICU 函数结合使用,以构造更复杂的字符串。 ```jsx copy import { declareVar, derive, useGT } from 'gt-react'; function Component({ name1, name2 }) { const gt = useGT(); const message = gt("Hello, {name1}! My name is " + derive(declareVar(name2)), { name1 }); return

{message}

; // 结果:"Hello, Brian! My name is Archie" } ``` *** ## 注意事项 * 仅在由 `derive` 调用的函数内使用 `declareVar` * 该函数会添加 ICU 标记,可能会干扰字符串处理 * 需要时,使用 `decodeVars` 提取原始值 * 变量不会被翻译,并会在 runtime 保留 ## 后续步骤 * 关于如何在字符串中创建静态函数调用,请参阅 [`derive`](/docs/react/api/strings/derive) * 关于如何提取原始值,请参阅 [`decodeVars`](/docs/react/api/strings/decode-vars) * 关于 JSX 中的对应组件,请参阅 [``](/docs/react/api/components/var)