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
Prop | Type | Default |
---|---|---|
[key]: string? | string | JSX.Element | - |
name?? | string | undefined |
children?? | any | undefined |
branch? | string | - |
[key]: string
语法表示代表潜在分支的任意键。
例如,可以将 active
和 inactive
等分支添加为参数。
Prop | 描述 |
---|---|
branch | 要渲染的分支名称。 |
children | 如果没有找到匹配的分支,则渲染的回退内容。 |
[key]: string | 代表给定分支值可能内容的分支。每个键对应一个分支,其值是要渲染的内容。 |
返回值
包含与指定分支对应的内容或回退内容的 JSX.Element
。
抛出异常
如果未提供 branch
prop 或其无效,则抛出 Error
。
示例
基本用法
<Branch>
需要为 branch
属性的每个可能值提供不同的输出。
在这个示例中,user.hairColor
值用于确定输出。
我们定义了 black
、brown
和 blonde
属性来匹配 user.hairColor
的可能值。
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
将始终用作回退。
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>
组件中。
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>
组件中。
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>
和用于动态内容的变量组件,以创建丰富的本地化界面。
下一步
这份指南怎么样?