# gt-next: General Translation Next.js SDK: declareVar URL: https://generaltranslation.com/zh/docs/next/api/strings/declare-var.mdx --- title: declareVar description: declareVar() 字符串函数的 API 参考文档 --- {/* 自动生成:请勿直接编辑。请改为编辑 content/docs-templates/ 中的模板。 */} ## 概述 在配合 `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/next/api/strings/decode-vars)。 **ICU 标记:** `declareVar` 会向源文本添加与 ICU 兼容的标记。如需进行字符串处理,可使用 `decodeVars` 提取原始值。 ## 参考 ### 参数 | Name | Type | Description | | --------------- | ----------------------------------------------------------- | ----------------------------------------------- | | `value` | ` value \| string \| number \| boolean\| undefined \| null` | 用于标记为变量的动态值。 | | `options?` | `Object` | `declareVar` 函数的配置选项。 | | `options.$name` | `string` | 变量名称,用于提供翻译上下文。 (类似于 `` 组件中的 `name` prop) | ### 返回值 一个包含与 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-next'; 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-next'; 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/next/api/strings/derive) * 关于如何提取原始值,请参阅 [`decodeVars`](/docs/next/api/strings/decode-vars) * 关于对应的 JSX 组件,请参阅 [``](/docs/next/api/components/var)