Components

<Plural>

<Plural> 组件的 API 参考

概述

我们使用 <Plural> 组件来处理句子的变形。 想想这两句话的区别:“You have one item.” 和 “You have two items.”

在英语中,你需要根据物品数量定义两种不同的句子。 而在其他语言中,你可能需要定义多达六种句子。

const count = 1;
<Plural n={count}
  singular={You have one item.}
  plural={You have some items.}
/>

参考

参数

PropTypeDefault
[key]: string?
string | JSX.Element
-
locales??
string[]
undefined
children??
any
undefined
n?
number
-

[key]: string 语法表示用于潜在复数分支的任意键。 例如,可以添加如 singularplural 这样的分支作为参数。

描述

参数名描述
n用于确定复数形式的数字。此参数是复数化所必需的。
children如果没有找到匹配的复数分支时渲染的备用内容。
locales可选的本地化参数,用于指定格式化的语言环境。如果未提供,则使用用户的默认语言环境。关于如何指定语言环境的更多信息请参见这里
[key]: string表示复数形式的分支。具体分支取决于所用的语言环境。

返回值

包含与 n 的复数形式对应内容的 JSX.Element,或备用内容。

异常

如果未提供 nn 不是有效数字,则抛出 Error


我应该添加哪些形式?

你只需要使用你语言中的复数形式。

可能的形式有:"singular""plural""dual""zero""one""two""few""many""other"

  • 如果你是使用 "en-US" 的开发者,只需使用两种形式:"singular""plural"
  • 如果你是 "zh-CN" 的开发者,只需使用 "other"

这里阅读更多关于不同形式的信息。


示例

基本用法

使用 <Plural> 组件来处理复数形式。

BasicExample.jsx
import { Plural } from 'gt-react';

export default function ItemCount({ count }) {
  return (
    <Plural n={count} 
      singular={You have one item.}
      plural={You have some items.}
    />
  );
}

备用内容

你可以为传递给 n 的值没有匹配分支的情况提供一个备用内容。

FallbackExample.jsx
import { Plural } from 'gt-react';

export default function ItemCount({ count }) {
  return (
    <Plural n={count}
      singular={You have one item.}
    >
      You have some items. // [!code highlight]
    </Plural>
  );
}

翻译复数

要进行翻译,只需添加 <T> 组件。

PluralExample.jsx
import { T, Plural } from 'gt-react';

export default function ItemCount({ count }) {
  return (
  <T id="itemCount">
    <Plural n={count}
      singular={You have an item.} 
      plural={You have some items.} 
    />
  );
}

添加变量

如果我们想在复数句子中添加一些变量怎么办?

PluralExample.jsx
import { T, Plural, Num } from 'gt-react';

export default function ItemCount({ count }) {
  return (
    <Plural n={count}
      singular={You have <Num>{count}</Num> item.} 
      plural={You have <Num>{count}</Num> items.} 
    />
  );
}

<T> 组件内部时,将所有动态内容用 <Currency><DateTime><Num><Var> 包裹起来。

<T id="itemCount">
  <Plural n={count}
    singular={You have <Num>{count}</Num> item.} 
    plural={You have <Num>{count}</Num> items.} 
  />
</T>

注意事项

  • <Plural> 组件用于处理复数形式。
  • 可用的复数分支(例如 one、other、few、many)取决于所选语言环境,并遵循 Unicode CLDR 复数规则

后续步骤

  • 想了解更多示例,请查看关于分支组件的参考文档 这里
  • 如需更高级的用法,可以将 <Plural><Currency><DateTime><Num><Var> 等变量组件结合使用。阅读更多关于变量组件的信息 这里

如需深入了解复数和分支处理,请访问 使用分支组件

这份指南怎么样?