React Native / TextInput ба маягт

TextInput ба маягт

Хэрэглэгчээс мэдээлэл авах нь бараг бүх аппд байдаг — нэвтрэх, бүртгүүлэх, хайлт хийх, мессеж илгээх. React Native-д TextInput component энэ бүх хэрэгцээг хангадаг. Энэ хичээлд TextInput-ийн тохиргоо болон бодит маягт хийхийг сурна.

TextInput үндэс

jsx
import { View, Text, TextInput, StyleSheet } from "react-native";
import { useState } from "react";

export default function App() {
  const [name, setName] = useState("");

  return (
    <View style={styles.container}>
      <Text style={styles.label}>Нэр</Text>
      <TextInput
        style={styles.input}
        value={name}
        onChangeText={setName}
        placeholder="Нэрээ оруулна уу"
        placeholderTextColor="#475569"
      />
      <Text style={styles.preview}>Таны нэр: {name}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: "#0b1120",
  },
  label: {
    fontSize: 14,
    color: "#94a3b8",
    marginBottom: 6,
  },
  input: {
    backgroundColor: "#0f172a",
    borderWidth: 1,
    borderColor: "#1e293b",
    borderRadius: 8,
    padding: 12,
    color: "#f1f5f9",
    fontSize: 15,
  },
  preview: {
    marginTop: 12,
    color: "#475569",
    fontSize: 14,
  },
});

value ба onChangeText хоёр нь хамт ажилладаг — энэ нь React-н controlled input загвар. onChangeText нь хэрэглэгч бичих бүрт шинэ утгыг дамжуулдаг.

TextInput-н чухал prop-ууд

jsx
{
  /* Нууц үг */
}
<TextInput
  secureTextEntry
  placeholder="Нууц үг"
  placeholderTextColor="#475569"
  style={styles.input}
/>;

{
  /* И-мэйл — автоматаар @ санал болгодог */
}
<TextInput
  keyboardType="email-address"
  autoCapitalize="none"
  autoCorrect={false}
  placeholder="И-мэйл хаяг"
  placeholderTextColor="#475569"
  style={styles.input}
/>;

{
  /* Олон мөр */
}
<TextInput
  multiline
  numberOfLines={4}
  textAlignVertical="top"
  placeholder="Тайлбар бичнэ үү..."
  placeholderTextColor="#475569"
  style={[styles.input, styles.textarea]}
/>;

keyboardType нь гарын төрлийг тохируулна — 'email-address', 'numeric', 'phone-pad' зэрэг утга авдаг. autoCapitalize="none" нь эхний үсгийг автоматаар томоор бичихгүй болгодог — и-мэйл, нууц үгэнд тохиромжтой.

Бодит маягт: нэвтрэх хуудас

jsx
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  Alert,
  StyleSheet,
} from "react-native";
import { useState } from "react";

export default function LoginForm() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);

  const handleLogin = async () => {
    if (!email || !password) {
      Alert.alert("Алдаа", "И-мэйл болон нууц үгийг оруулна уу.");
      return;
    }
    setLoading(true);
    // Энд Supabase auth дуудагдана
    setTimeout(() => {
      setLoading(false);
      Alert.alert("Амжилт!", "Нэвтэрлээ.");
    }, 1500);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Нэвтрэх</Text>

      <View style={styles.field}>
        <Text style={styles.label}>И-мэйл</Text>
        <TextInput
          style={styles.input}
          value={email}
          onChangeText={setEmail}
          placeholder="name@example.com"
          placeholderTextColor="#475569"
          keyboardType="email-address"
          autoCapitalize="none"
          autoCorrect={false}
        />
      </View>

      <View style={styles.field}>
        <Text style={styles.label}>Нууц үг</Text>
        <TextInput
          style={styles.input}
          value={password}
          onChangeText={setPassword}
          placeholder="••••••••"
          placeholderTextColor="#475569"
          secureTextEntry
        />
      </View>

      <TouchableOpacity
        style={[styles.button, loading && styles.buttonDisabled]}
        onPress={handleLogin}
        disabled={loading}
      >
        <Text style={styles.buttonText}>
          {loading ? "Нэвтэрч байна..." : "Нэвтрэх"}
        </Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    padding: 24,
    backgroundColor: "#0b1120",
  },
  title: {
    fontSize: 26,
    fontWeight: "bold",
    color: "#f1f5f9",
    marginBottom: 32,
  },
  field: { marginBottom: 16 },
  label: { fontSize: 14, color: "#94a3b8", marginBottom: 6 },
  input: {
    backgroundColor: "#0f172a",
    borderWidth: 1,
    borderColor: "#1e293b",
    borderRadius: 8,
    padding: 13,
    color: "#f1f5f9",
    fontSize: 15,
  },
  button: {
    backgroundColor: "#22d3ee",
    padding: 14,
    borderRadius: 10,
    alignItems: "center",
    marginTop: 8,
  },
  buttonDisabled: { opacity: 0.6 },
  buttonText: { color: "#0b1120", fontWeight: "bold", fontSize: 16 },
});

Focus ба blur удирдах

onFocus ба onBlur ашиглан талбар сонгогдоход харагдах байдлыг өөрчилж болно:

jsx
import { useState } from "react";
import { TextInput, StyleSheet } from "react-native";

export default function FocusInput() {
  const [focused, setFocused] = useState(false);

  return (
    <TextInput
      style={[styles.input, focused && styles.inputFocused]}
      onFocus={() => setFocused(true)}
      onBlur={() => setFocused(false)}
      placeholder="Дарж бичнэ үү"
      placeholderTextColor="#475569"
    />
  );
}

const styles = StyleSheet.create({
  input: {
    backgroundColor: "#0f172a",
    borderWidth: 1,
    borderColor: "#1e293b",
    borderRadius: 8,
    padding: 12,
    color: "#f1f5f9",
    fontSize: 15,
  },
  inputFocused: {
    borderColor: "#22d3ee",
  },
});

Талбар сонгогдоход хүрээний өнгө цэнхэр болж өөрчлөгдөнө — хэрэглэгчид ямар талбар дээр байгааг тодорхой мэдэгддэг.

Дараагийн хичээлд:

TextInput ба маягт хийж сурлаа. Дараагийн хичээлд Image компонент — дэлгэцэнд зураг харуулах, сүлжээнээс зураг татах, зургийг яг тааруулах аргуудыг судална.