Components

<Branch>

<Branch> 组件的 API 参考

概述

<Branch> 组件允许您向翻译添加条件逻辑。

const status = 'active';
<Branch branch={status}
    active={<p>The user is active.</p>}
    inactive={<p>The user is inactive.</p>}
/>

您向 branch 参数传递一个值,该值会根据您提供的键与输出值进行匹配。

参考

Props

PropTypeDefault
[key]: string?
string | JSX.Element
-
name??
string
undefined
children??
any
undefined
branch?
string
-

[key]: string 语法表示代表潜在分支的任意键。 例如,可以将 activeinactive 等分支添加为参数。

Prop描述
branch要渲染的分支名称。
children如果没有找到匹配的分支,则渲染的回退内容。
[key]: string代表给定分支值可能内容的分支。每个键对应一个分支,其值是要渲染的内容。

返回值

包含与指定分支对应的内容或回退内容的 JSX.Element

抛出异常

如果未提供 branch prop 或其无效,则抛出 Error

示例

基本用法

<Branch> 需要为 branch 属性的每个可能值提供不同的输出。

在这个示例中,user.hairColor 值用于确定输出。 我们定义了 blackbrownblonde 属性来匹配 user.hairColor 的可能值。

BranchExample.jsx
import { Branch } from 'gt-next';

export default function HairColor({ user }) {
  return (
    <Branch branch={user.hairColor}
      black={<p>Their hair is dark.</p>}
      brown="Their hair is in the middle." // (you can pass a string if you prefer)
      blonde={<p>Their hair is light.</p>}
    />
  );
}

回退内容

如果没有属性匹配传递给 branch 的值,children 将始终用作回退。

BranchExample.jsx
import { Branch } from 'gt-next';

export default function HairColor({ user }) {
  return (
    <Branch branch={user.hairColor}
      black={<p>Their hair is dark.</p>}
      brown={<p>Their hair is in the middle.</p>}
      blonde={<p>Their hair is light.</p>}
    >
      <p>Their hair is unknown.</p> // [!code highlight]
    </Branch>
  );
}

翻译 <Branch>

如果你想翻译内容,只需将其包装在 <T> 组件中。

BranchExample.jsx
import { T, Branch } from 'gt-next';

export default function HairColor({ user }) {
  return (
    <T id="example">
      <Branch branch={user.hairColor}
        black={<p>Their hair is dark.</p>}
        brown={<p>Their hair is in the middle.</p>}
        blonde={<p>Their hair is light.</p>}
      >
        <p>Their hair is unknown.</p> 
      </Branch>
    </T> 
  );
}

添加变量

如果你想在分支中渲染动态值,请确保将它们包装在 <Currency><DateTime><Num><Var> 组件中。

BranchExample.jsx
import { Branch, T, Var } from 'gt-next';

export default function HairColor({ user }) {
  return (
    <T id="example">
      <Branch branch={user.hairColor}
        black={<p>Their hair is dark.</p>}
        brown={<p>Their hair is in the middle.</p>}
        blonde={<p>Their hair is light.</p>}
      >
        <p>Unhandled hair color: <Var>{user.hairColor}</Var></p>
      </Branch>
    </T>
  );
}

注意事项

  • 分支的键可以是任何与 branch 属性匹配的字符串值。这种灵活性使得 <Branch> 能够轻松适应各种使用场景。
  • <Branch> 与其他组件结合使用,例如用于翻译的 <T> 和用于动态内容的变量组件,以创建丰富的本地化界面。

下一步

  • 有关更高级的用法和示例,请参阅使用分支组件
  • 要了解更多关于变量组件如 <Currency><DateTime><Num><Var> 的信息,请查看使用变量组件文档。

这份指南怎么样?