# react-native: Локализуйте Mini Shop
URL: https://generaltranslation.com/ru/docs/react-native/tutorials/mini-shop.mdx
---
title: Локализуйте Mini Shop
description: Пошаговое руководство по React Native, в котором вы локализуете простой магазин с помощью компонентов GT React Native, хуков и общих строк
---
`gt-react-native` всё ещё находится на экспериментальной стадии и может работать не во всех проектах.
Если вы столкнётесь с какими-либо проблемами, пожалуйста, сообщите нам об этом, [создав issue на GitHub](https://github.com/generaltranslation/gt/issues).
Вы запустите небольшой полностью локальный «мини-магазин» с переводом в React Native — без внешних сервисов, роутинга и UI-фреймворков, кроме Expo. Вы последовательно пройдёте по основным возможностям GT React Native и увидите, как они сочетаются в простом, реалистичном мобильном интерфейсе.
Требования: React Native (Expo), базовые знания JavaScript/TypeScript
Что вы создадите
* Одноэкранный «магазин» со списком товаров и простой корзиной в памяти
* Переключатель языка и общие метки навигации
* Корректно локализованные числа, валюта и формы множественного числа
Ссылки, используемые в этом руководстве
* провайдер: [``](/docs/react-native/api/components/gtprovider)
* Компоненты: [``](/docs/react-native/api/components/t), [``](/docs/react-native/api/components/var), [``](/docs/react-native/api/components/num), [``](/docs/react-native/api/components/currency), [``](/docs/react-native/api/components/datetime), [``](/docs/react-native/api/components/branch), [``](/docs/react-native/api/components/plural), [``](/docs/react-native/api/components/locale-selector)
* Строки и общие строки: [`useGT`](/docs/react-native/api/strings/use-gt), [`msg`](/docs/react-native/api/strings/msg), [`useMessages`](/docs/react-native/api/strings/use-messages)
* Руководства: [Переменные](/docs/react-native/guides/variables), [Ветвление](/docs/react-native/guides/branches), [Строки](/docs/react-native/guides/strings), [Локальное хранилище переводов](/docs/react-native/guides/local-tx), [Смена языка](/docs/react-native/guides/languages)
***
## Установите пакеты и оберните приложение в провайдер
Установите пакеты и оберните приложение в провайдер.
```bash
npm i gt-react-native
npm i --save-dev gt
```
```bash
yarn add gt-react-native
yarn add --dev gt
```
```bash
bun add gt-react-native
bun add --dev gt
```
```bash
pnpm add gt-react-native
pnpm add --save-dev gt
```
Необязательно: стартовый проект (Expo)
Если вы начинаете с нуля, сначала создайте приложение Expo, а затем установите пакеты GT:
```bash copy
npx create-expo-app mini-shop --template blank-typescript
cd mini-shop
npm i gt-react-native
npm i --save-dev gt
```
Затем добавьте файлы из разделов ниже (например, `App.tsx`, `components/*`, `data.ts`, `nav.ts`).
Создайте минимальную конфигурацию провайдера.
```tsx title="App.tsx" copy
import { GTProvider } from 'gt-react-native';
import Shop from './Shop';
export default function App() {
return (
);
}
```
При желании можете уже сейчас добавить `gt.config.json` (позже это пригодится для CI и локального хранилища):
```json title="gt.config.json" copy
{
"defaultLocale": "en",
"locales": ["es", "fr"]
}
```
### API-ключи для разработки
Вы можете пройти это руководство без ключей (в этом случае будет отображаться язык по умолчанию). Чтобы видеть переводы в реальном времени и тестировать переключение языков во время разработки, добавьте ключи разработки.
Подробнее см. в разделе [Production vs Development](/docs/react-native/concepts/environments).
```bash title=".env" copy
EXPO_PUBLIC_GT_API_KEY="your-dev-api-key"
EXPO_PUBLIC_GT_PROJECT_ID="your-project-id"
```
* Панель управления: https://dash.generaltranslation.com/signup
* Или через CLI:
```bash copy
npx gt auth
```
***
## Начальные данные и структура приложения
Мы прямо в коде зададим небольшой массив товаров и оставим всё на стороне клиента. Без сервера и навигации.
```ts title="data.ts" copy
export type Product = {
id: string;
name: string;
description: string;
price: number;
currency: 'USD' | 'EUR';
inStock: boolean;
addedAt: string; // строка даты в формате ISO
};
export const products: Product[] = [
{
id: 'p-1',
name: 'Wireless Headphones',
description: 'Noise-cancelling over-ear design with 30h battery',
price: 199.99,
currency: 'USD',
inStock: true,
addedAt: new Date().toISOString()
},
{
id: 'p-2',
name: 'Travel Mug',
description: 'Double-wall insulated stainless steel (12oz)',
price: 24.5,
currency: 'USD',
inStock: false,
addedAt: new Date().toISOString()
}
];
```
***
## Общие метки навигации с msg и useMessages
Используйте [`msg`](/docs/react-native/api/strings/msg), чтобы помечать общие строки в конфигурации, а затем декодируйте их через [`useMessages`](/docs/react-native/api/strings/use-messages) при рендеринге.
```tsx title="nav.ts" copy
import { msg } from 'gt-react-native';
export const navItems = [
{ label: msg('Home'), id: 'home' },
{ label: msg('Products'), id: 'products' },
{ label: msg('Cart'), id: 'cart' }
];
```
```tsx title="components/Header.tsx" copy
import { View, Text, StyleSheet } from 'react-native';
import { LocaleSelector, T } from 'gt-react-native';
import { useMessages } from 'gt-react-native';
import { navItems } from '../nav';
export default function Header() {
const m = useMessages();
return (
Mini Shop
{navItems.map(item => (
{m(item.label)}
))}
);
}
const styles = StyleSheet.create({
header: {
paddingVertical: 16,
paddingHorizontal: 12,
borderBottomWidth: 1,
borderBottomColor: '#eee',
},
title: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 8,
},
nav: {
flexDirection: 'row',
gap: 12,
marginBottom: 8,
},
navItem: {
fontSize: 14,
color: '#555',
},
});
```
***
## Карточки товаров с T, переменными, Branch и Currency
Используйте [``](/docs/react-native/api/components/t) для перевода JSX. Оборачивайте динамические данные в компоненты переменных, такие как [``](/docs/react-native/api/components/var), [``](/docs/react-native/api/components/num), [``](/docs/react-native/api/components/currency) и [``](/docs/react-native/api/components/datetime). Управляйте состоянием наличия на складе с помощью [``](/docs/react-native/api/components/branch).
```tsx title="components/ProductCard.tsx" copy
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import { T, Var, Currency, DateTime, Branch } from 'gt-react-native';
import type { Product } from '../data';
export default function ProductCard({ product, onAdd }: { product: Product; onAdd: () => void }) {
return (
{product.name}
{product.description}
Price: {product.price}
Added: {product.addedAt}
In stock}
false={Out of stock}
/>
Add to cart
);
}
const styles = StyleSheet.create({
card: {
borderWidth: 1,
borderColor: '#ddd',
borderRadius: 8,
padding: 12,
marginBottom: 12,
},
name: {
fontSize: 18,
fontWeight: '600',
marginBottom: 4,
},
description: {
fontSize: 14,
color: '#666',
marginBottom: 8,
},
price: {
fontSize: 16,
marginBottom: 4,
},
date: {
fontSize: 12,
color: '#999',
marginBottom: 8,
},
inStock: {
color: 'green',
marginBottom: 8,
},
outOfStock: {
color: 'tomato',
marginBottom: 8,
},
button: {
backgroundColor: '#007AFF',
paddingVertical: 10,
borderRadius: 6,
alignItems: 'center',
},
buttonDisabled: {
backgroundColor: '#ccc',
},
buttonText: {
color: '#fff',
fontWeight: '600',
},
});
```
***
## Корзина: множественное число и итоговая сумма
Используйте [``](/docs/react-native/api/components/plural), чтобы выразить "X товаров в корзине", а [``](/docs/react-native/api/components/currency) — для итоговой суммы. Комбинируйте с [``](/docs/react-native/api/components/t), [``](/docs/react-native/api/components/var) и [``](/docs/react-native/api/components/num).
```tsx title="components/Cart.tsx" copy
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import { T, Plural, Var, Num, Currency } from 'gt-react-native';
import type { Product } from '../data';
export default function Cart({ items, onClear }: { items: Product[]; onClear: () => void }) {
const total = items.reduce((sum, p) => sum + p.price, 0);
const itemCount = items.length;
return (
Cart
Your cart is empty}
one={You have {itemCount} item}
other={You have {itemCount} items}
/>
{items.map((p) => (
{p.name} — {p.price}
))}
Total: {total}
Clear cart
);
}
const styles = StyleSheet.create({
container: {
borderTopWidth: 1,
borderTopColor: '#eee',
paddingTop: 16,
marginTop: 16,
},
heading: {
fontSize: 20,
fontWeight: 'bold',
marginBottom: 8,
},
empty: {
color: '#999',
marginBottom: 8,
},
item: {
fontSize: 14,
marginVertical: 4,
},
total: {
fontSize: 16,
fontWeight: '600',
marginTop: 8,
marginBottom: 12,
},
button: {
backgroundColor: '#FF3B30',
paddingVertical: 10,
borderRadius: 6,
alignItems: 'center',
},
buttonDisabled: {
backgroundColor: '#ccc',
},
buttonText: {
color: '#fff',
fontWeight: '600',
},
});
```
***
## Атрибуты и заполнители с `useGT`
Используйте [`useGT`](/docs/react-native/api/strings/use-gt) для перевода обычных строк, например заполнителей полей ввода и меток доступности.
```tsx title="components/Search.tsx" copy
import { TextInput, StyleSheet } from 'react-native';
import { useGT } from 'gt-react-native';
export default function Search({ onQuery }: { onQuery: (q: string) => void }) {
const gt = useGT();
return (
);
}
const styles = StyleSheet.create({
input: {
borderWidth: 1,
borderColor: '#ddd',
borderRadius: 8,
padding: 10,
fontSize: 16,
},
});
```
***
## Соберём всё вместе
Одноэкранное приложение с корзиной, хранящейся в памяти, и простым фильтром поиска.
```tsx title="Shop.tsx" copy
import { useMemo, useState } from 'react';
import { SafeAreaView, ScrollView, View, StyleSheet } from 'react-native';
import Header from './components/Header';
import Search from './components/Search';
import ProductCard from './components/ProductCard';
import Cart from './components/Cart';
import { products } from './data';
export default function Shop() {
const [query, setQuery] = useState('');
const [cart, setCart] = useState([]);
const filtered = useMemo(() => {
const q = query.toLowerCase();
return products.filter(p =>
p.name.toLowerCase().includes(q) || p.description.toLowerCase().includes(q)
);
}, [query]);
const items = products.filter(p => cart.includes(p.id));
return (
{filtered.map(p => (
setCart(c => (p.inStock ? [...new Set([...c, p.id])] : c))}
/>
))}
setCart([])}
/>
);
}
const styles = StyleSheet.create({
safe: {
flex: 1,
backgroundColor: '#fff',
},
scroll: {
padding: 16,
},
searchContainer: {
marginVertical: 12,
},
products: {
gap: 0,
},
});
```
***
## Запуск локально
Запустите сервер разработки Expo:
```bash
npx expo start
```
Затем откройте приложение в Expo Go на телефоне или нажмите `i`, чтобы запустить симулятор iOS, или `a`, чтобы запустить эмулятор Android.
***
## Что вы узнали
* Как переводить JSX с помощью [``](/docs/react-native/api/components/t) и работать с динамическим содержимым через [``](/docs/react-native/api/components/var), [``](/docs/react-native/api/components/num), [``](/docs/react-native/api/components/currency), [``](/docs/react-native/api/components/datetime)
* Как задавать условное содержимое с помощью [``](/docs/react-native/api/components/branch) и количественные формы с помощью [``](/docs/react-native/api/components/plural)
* Как переводить атрибуты с помощью [`useGT`](/docs/react-native/api/strings/use-gt)
* Как переиспользовать строки навигации и конфигурации через [`msg`](/docs/react-native/api/strings/msg) и декодировать их с помощью [`useMessages`](/docs/react-native/api/strings/use-messages)
* Как переключать языки с помощью [``](/docs/react-native/api/components/locale-selector)
## Что дальше
* Ознакомьтесь с материалами: [Руководство по переменным](/docs/react-native/guides/variables), [Руководство по ветвлению](/docs/react-native/guides/branches), [Руководство по строкам](/docs/react-native/guides/strings), [Смена языка](/docs/react-native/guides/languages)