Задайте вопрос и получите краткое содержание документа через любого ИИ-провайдера на этой странице
Этот документ устарел, базовая версия была обновлена 23 августа 2025 г..
Перейти к английской документацииИстория версий
- "Инициализация истории"v5.5.1029.06.2025
Содержимое этой страницы было переведено с помощью ИИ.
Смотреть последнюю версию оригинального контента на английскомIf you have an idea for improving this documentation, please feel free to contribute by submitting a pull request on GitHub.
GitHub link to the documentationCopy doc Markdown to clipboard
Перечисление / Множественное число
Как работает перечисление
To use enumeration in a React component, you can leverage the useIntlayer hook from the react-intlayer package. This hook retrieves the correct content based on the specified ID. Here's an example of how to use it:
Копировать код в буфер обмена
import type { FC } from "react";
import { useIntlayer } from "react-intlayer";
const CarComponent: FC = () => {
const { numberOfCar } = useIntlayer("car_count");
return (
<div>
<p>
{
numberOfCar(0) // Output: No cars
}
</p>
<p>
{
numberOfCar(6) // Output: Some cars
}
</p>
<p>
{
numberOfCar(20) // Output: Many cars
}
</p>
<p>
{
numberOfCar(0.01) // Output: Fallback value
}
</p>
</div>
);
};Настройка перечисления
Чтобы настроить перечисление в вашем проекте Intlayer, необходимо создать модуль содержимого, включающий определения перечислений. Вот пример простого перечисления для количества автомобилей:
Копировать код в буфер обмена
import { enu, type Dictionary } from "intlayer";
const carEnumeration = {
key: "car_count",
content: {
numberOfCar: enu({
"<-1": "Меньше чем минус один автомобиль",
"-1": "Минус один автомобиль",
"0": "Нет автомобилей",
"1": "Один автомобиль",
">5": "Несколько автомобилей",
">19": "Много автомобилей",
"fallback": "Запасное значение", // Необязательно
}),
},
} satisfies Dictionary;
export default carEnumeration;В этом примере enu сопоставляет различные условия с конкретным содержимым. При использовании в React-компоненте Intlayer может автоматически выбирать соответствующее содержимое на основе переданной переменной.
Порядок объявления важен в перечислениях Intlayer. Первое подходящее объявление будет выбрано. Если применяются несколько условий, убедитесь, что они расположены в правильном порядке, чтобы избежать непредвиденного поведения.
Если запасное значение не объявлено, функция вернёт undefined, если ни один ключ не совпадает.
Использование перечислений с React Intlayer
To use enumeration in a React component, you can leverage the useIntlayer hook from the react-intlayer package. This hook retrieves the correct content based on the specified ID. Here's an example of how to use it:
Копировать код в буфер обмена
import type { FC } from "react";
import { useIntlayer } from "react-intlayer";
const CarComponent: FC = () => {
const { numberOfCar } = useIntlayer("car_count");
return (
<div>
<p>
{
numberOfCar(0) // Output: No cars
}
</p>
<p>
{
numberOfCar(6) // Output: Some cars
}
</p>
<p>
{
numberOfCar(20) // Output: Many cars
}
</p>
<p>
{
numberOfCar(0.01) // Output: Fallback value
}
</p>
</div>
);
};Combining Enumeration with Insert for Ordinal Numbers
A common use case is displaying ordinal numbers (1st, 2nd, 3rd, etc.). You can combine enu with insert to create dynamic ordinal content:
Копировать код в буфер обмена
import { enu, insert, type Dictionary } from "intlayer";
const rankingContent = {
key: "ranking_component",
content: {
ordinal: enu({
1: insert("{{count}}st place"),
2: insert("{{count}}nd place"),
3: insert("{{count}}rd place"),
fallback: insert("{{count}}th place"),
}),
},
} satisfies Dictionary;
export default rankingContent;Using Ordinal Enumeration
To use this in a React component, call the enumeration with the last digit of the number to get the correct suffix, then pass the full count as the insertion value:
Копировать код в буфер обмена
import type { FC } from "react";
import { useIntlayer } from "react-intlayer";
const RankingComponent: FC<{ count: number }> = ({ count }) => {
const { ordinal } = useIntlayer("ranking_component");
// Get the last digit to determine the correct suffix
const lastDigit = Math.abs(count) % 10;
return (
<div>
<p>
{
ordinal(lastDigit)({ count }) // e.g., "5th place" for count=5
}
</p>
</div>
);
};Additional Resources
For more detailed information on configuration and usage, refer to the following resources:
These resources provide further insights into the setup and usage of Intlayer in different environments and with various frameworks.