7. TextInput и формы
TextInput — основной компонент для ввода текста. Поддерживает все типы клавиатуры, маскировку пароля, многострочный ввод.
Базовое использование
Заголовок раздела «Базовое использование»import { TextInput, useState } from 'react-native';
const [text, setText] = useState('');
<TextInput value={text} onChangeText={setText} placeholder="Введите текст..." placeholderTextColor="#6c7086" style={styles.input}/>Типы клавиатуры
Заголовок раздела «Типы клавиатуры»// keyboardType определяет раскладку клавиатуры<TextInput keyboardType="default" /> // обычная<TextInput keyboardType="numeric" /> // только цифры<TextInput keyboardType="email-address" /> // email (@)<TextInput keyboardType="phone-pad" /> // номер телефона<TextInput keyboardType="decimal-pad" /> // десятичные<TextInput keyboardType="url" /> // URL (.)Пароль и secure input
Заголовок раздела «Пароль и secure input»<TextInput secureTextEntry={true} // Скрывает символы autoCapitalize="none" // Без заглавных autoCorrect={false} // Без автокоррекции/>returnKeyType — кнопка “Enter”
Заголовок раздела «returnKeyType — кнопка “Enter”»<TextInput returnKeyType="done" // Готово returnKeyType="next" // Следующее поле returnKeyType="search" // Поиск returnKeyType="send" // Отправить returnKeyType="go" // Перейти onSubmitEditing={() => nextInputRef.current?.focus()}/>Многострочный ввод
Заголовок раздела «Многострочный ввод»<TextInput multiline={true} numberOfLines={4} // Android: начальная высота style={{ height: 100, textAlignVertical: 'top' }} // textAlignVertical для Android onChangeText={setText}/>ref для управления фокусом
Заголовок раздела «ref для управления фокусом»import { useRef } from 'react';
const nameRef = useRef(null);const emailRef = useRef(null);
<TextInput ref={nameRef} returnKeyType="next" onSubmitEditing={() => emailRef.current?.focus()}/><TextInput ref={emailRef} returnKeyType="done"/>
// Программный фокус<Button title="Фокус" onPress={() => nameRef.current?.focus()} />Полная форма авторизации
Заголовок раздела «Полная форма авторизации»import { View, TextInput, TouchableOpacity, Text, StyleSheet } from 'react-native';import { useState, useRef } from 'react';
export default function LoginForm() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [loading, setLoading] = useState(false); const passwordRef = useRef(null);
const handleLogin = async () => { setLoading(true); try { await loginAPI(email, password); } finally { setLoading(false); } };
return ( <View style={styles.form}> <TextInput style={styles.input} value={email} onChangeText={setEmail} placeholder="Email" keyboardType="email-address" autoCapitalize="none" autoCorrect={false} returnKeyType="next" onSubmitEditing={() => passwordRef.current?.focus()} /> <TextInput ref={passwordRef} style={styles.input} value={password} onChangeText={setPassword} placeholder="Пароль" secureTextEntry returnKeyType="done" onSubmitEditing={handleLogin} /> <TouchableOpacity style={[styles.button, loading && { opacity: 0.7 }]} onPress={handleLogin} disabled={loading || !email || !password} > <Text style={styles.buttonText}> {loading ? 'Входим...' : 'Войти'} </Text> </TouchableOpacity> </View> );}