# react-native: Branch URL: https://generaltranslation.com/zh/docs/react-native/api/components/branch.mdx --- title: Branch description: Branch 组件 API 参考 --- {/* 自动生成:请勿直接编辑。请改为编辑 content/docs-templates/ 中的 template。 */} ## 概述 `` 组件允许你为翻译添加条件逻辑。 ```jsx const status = 'active'; The user is active.

} inactive={

The user is inactive.

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

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

Their hair is light.

} /> ); } ``` ### 后备内容 如果没有任何 属性 与传给 `branch` 的值匹配,`children` 将始终作为后备内容使用。 ```jsx title="BranchExample.jsx" copy import { Branch } from 'gt-react-native'; 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]
); } ``` ### 翻译 Branch 如果要翻译这段内容,请将其包裹在 `` 组件中。 ```jsx title="BranchExample.jsx" copy import { T, Branch } from 'gt-react-native'; 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] ); } ``` ### 添加变量 如果你想在 branch 中渲染动态值,请务必用 ``、``、`` 或 `` 组件将它们包裹起来。 ```jsx title="BranchExample.jsx" copy import { Branch, T, Var } from 'gt-react-native'; 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 的键可以是任何与 branch 属性 匹配的字符串值。这样的灵活性让你可以轻松将 `` 适配到各种用例。 * 将 `` 与其他组件配合使用,例如用于翻译的 `` 和用于动态内容的[变量组件](/docs/react-native/guides/variables),即可构建丰富且本地化的界面。 ## 后续步骤 * 如需了解更高级的用法和示例,请参阅[使用 Branching Components](/docs/react-native/guides/branches)。