React Native【实战范例】登录页(含密码显示隐藏)

发布于:2025-06-14 ⋅ 阅读:(21) ⋅ 点赞:(0)

在这里插入图片描述

import React, { useState } from "react";
import {
  Button,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import {
  SafeAreaProvider,
  useSafeAreaInsets,
} from "react-native-safe-area-context";
const LoginForm = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const handleLogin = () => {
    console.log("登录:", email, password);
  };
  return (
    <View style={styles.container}>
      <TextInput
        style={styles.inputStyle}
        placeholder="邮箱"
        keyboardType="email-address"
        autoCapitalize="none"
        onChangeText={setEmail}
        value={email}
      />
      <View style={styles.passwordContainer}>
        <TextInput
          style={styles.inputStyle}
          placeholder="密码"
          secureTextEntry={!showPassword}
          onChangeText={setPassword}
          value={password}
        />
        <TouchableOpacity
          style={styles.togglePasswordButton}
          onPress={() => setShowPassword(!showPassword)}
        >
          <Text style={styles.togglePasswordButtonText}>
            {showPassword ? "隐藏" : "显示"}
          </Text>
        </TouchableOpacity>
      </View>
      <Button title="登录" onPress={handleLogin} />
    </View>
  );
};
export default function HomeScreen() {
  const insets = useSafeAreaInsets();
  return (
    <SafeAreaProvider>
      <View
        style={{
          flex: 1,
          paddingTop: insets.top, // 顶部安全区域
          paddingBottom: insets.bottom, // 底部安全区域
        }}
      >
        <LoginForm />
      </View>
    </SafeAreaProvider>
  );
}
const styles = StyleSheet.create({
  container: {
    padding: 20,
  },
  inputStyle: {
    height: 40,
    borderColor: "gray",
    borderWidth: 1,
    marginVertical: 10,
    paddingHorizontal: 10,
    flex: 1,
  },
  passwordContainer: {
    flexDirection: "row",
    alignItems: "center",
  },
  togglePasswordButton: {
    height: 40,
    width: 60,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#2296f3",
  },
  togglePasswordButtonText: {
    color: "#fff",
  },
});