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
参数,然后它会根据你提供的键与输出值进行匹配。
参考
属性
Prop | Type | Default |
---|---|---|
[key]: string? | string | JSX.Element | - |
name?? | string | undefined |
children?? | any | undefined |
branch? | string | - |
[key]: string
语法表示任意键,用于表示可能的分支。
例如,可以添加 active
和 inactive
这样的分支作为参数。
属性 | 描述 |
---|---|
branch | 要渲染的分支名称。 |
children | 如果未找到匹配的分支时渲染的备用内容。 |
[key]: string | 表示给定分支值可能内容的分支。每个键对应一个分支,其值为要渲染的内容。 |
返回值
包含指定分支内容或备用内容的 JSX.Element
。
异常
如果未提供或提供了无效的 branch
属性,则抛出 Error
。
示例
基本用法
<Branch>
需要针对 branch
属性的每个可能值输出不同的内容。
在这个例子中,user.hairColor
的值被用来决定输出内容。
我们定义了 black
、brown
和 blonde
这几个属性,以匹配 user.hairColor
的可能取值。
import { Branch } from 'gt-react';
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-react';
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-react';
export default function HairColor({ user }) {
return (
<T id="example"> // [!code highlight]
<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-react';
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> // [!code highlight]
</Branch>
</T>
);
}
注意事项
- 分支的键可以是任何与 branch 属性匹配的字符串值。这种灵活性使得
<Branch>
能够轻松适应各种使用场景。 - 将
<Branch>
与其他组件结合使用,例如用于翻译的<T>
以及用于动态内容的变量组件,可以创建丰富且本地化的界面。
后续步骤
这份指南怎么样?