Перейти к содержимому

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 (.)
<TextInput
secureTextEntry={true} // Скрывает символы
autoCapitalize="none" // Без заглавных
autoCorrect={false} // Без автокоррекции
/>
<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}
/>
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>
);
}