# gt-next: General Translation Next.js SDK: Branch URL: https://generaltranslation.com/zh/docs/next/api/components/branch.mdx --- title: Branch description: Branch 组件 API 参考 --- {/* 自动生成:请勿直接编辑。请改为编辑 content/docs-templates/ 中的模板。 */} ## 概述 `` 组件可让你在翻译中添加条件逻辑。 ```jsx const status = 'active'; The user is active.

} inactive={

The user is inactive.

} /> ``` 你向 `branch` 参数传入一个值,系统会根据你提供的键将其匹配到对应的输出值。 ## 参考 ### Props `[key]: string` 语法表示可用于表示不同分支的任意键。 例如,可以将 `active` 和 `inactive` 这类分支作为参数添加。 | Prop | Description | | --------------- | ------------------------------------- | | `branch` | 要渲染的分支名称。 | | `children` | 如果未找到匹配的分支,则渲染此回退内容。 | | `[key]: string` | 表示给定分支值对应的可选内容分支。每个键对应一个分支,其值为要渲染的内容。 | ### 返回值 包含与指定分支对应的内容或回退内容的 `JSX.Element`。 ### 抛出 如果未提供 `branch` prop,或其值无效,则会抛出 `Error`。 ## 示例 ### 基本用法 `` 需要为 `branch` prop 的每个可能取值输出不同的内容。 在这个示例中,输出内容由 `user.hairColor` 的值决定。 我们定义了 `black`、`brown` 和 `blonde` 这几个 prop,分别对应 `user.hairColor` 的可能取值。 ```jsx title="BranchExample.jsx" copy import { Branch } from 'gt-next'; export default function HairColor({ user }) { return ( Their hair is dark.

} brown="Their hair is in the middle." // (也可以直接传入字符串) blonde={

Their hair is light.

} /> ); } ``` ### 回退内容 如果没有任何 prop 与传给 `branch` 的值匹配,始终会使用 `children` 作为回退内容。 ```jsx title="BranchExample.jsx" copy import { Branch } from 'gt-next'; export default function HairColor({ user }) { return ( Their hair is dark.

} brown={

Their hair is in the middle.

} blonde={

Their hair is light.

} >

Their hair is unknown.

// [!code highlight]
); } ``` ### 翻译一段内容 如果你想翻译这段内容,请将它包裹在 `` 组件中。 ```jsx title="BranchExample.jsx" copy import { T, Branch } from 'gt-next'; export default function HairColor({ user }) { return ( // [!code highlight] Their hair is dark.

} brown={

Their hair is in the middle.

} blonde={

Their hair is light.

} >

Their hair is unknown.

// [!code highlight] ); } ``` ### 添加变量 如果你想在分支中渲染动态值,请务必使用 ``、``、`` 或 `` 组件将它们包裹起来。 ```jsx title="BranchExample.jsx" copy import { Branch, T, Var } from 'gt-next'; export default function HairColor({ user }) { return ( Their hair is dark.

} brown={

Their hair is in the middle.

} blonde={

Their hair is light.

} >

Unhandled hair color: {user.hairColor}

// [!code highlight]
); } ``` *** ## 说明 * 分支键可以是任何与 `branch` prop 匹配的字符串值。这种灵活性让 `` 能轻松适用于各种使用场景。 * 可将 `` 与其他组件结合使用,例如用于翻译的 `` 以及用于动态内容的[变量组件](/docs/next/guides/variables),以构建丰富的本地化界面。 ## 后续步骤 * 如需了解更高级的用法和更多示例,请参阅[使用 Branching Components](/docs/next/guides/branches)。