# gt-react: General Translation React SDK: Branch
URL: https://generaltranslation.com/zh/docs/react/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-react';
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-react';
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-react';
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-react';
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/react/guides/variables),即可构建丰富的本地化界面。
## 后续步骤
* 如需了解更高级的用法和示例,请参阅 [使用分支组件](/docs/react/guides/branches)。