react native实现登录界面
以下是在React Native中实现登录界面的方法和代码示例:
基本结构搭建
使用react-native init创建项目后,在App.js或单独组件文件中构建登录界面基础结构:
import React, { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet, Alert } from 'react-native';
const LoginScreen = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleLogin = () => {
if (!email || !password) {
Alert.alert('错误', '请输入邮箱和密码');
return;
}
// 这里添加登录逻辑
console.log('登录信息:', { email, password });
};
return (
<View style={styles.container}>
<Text style={styles.title}>用户登录</Text>
<TextInput
style={styles.input}
placeholder="邮箱"
value={email}
onChangeText={setEmail}
keyboardType="email-address"
autoCapitalize="none"
/>
<TextInput
style={styles.input}
placeholder="密码"
value={password}
onChangeText={setPassword}
secureTextEntry
/>
<Button title="登录" onPress={handleLogin} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
padding: 20,
},
title: {
fontSize: 24,
marginBottom: 20,
textAlign: 'center',
},
input: {
height: 40,
borderColor: 'gray',
borderWidth: 1,
marginBottom: 15,
paddingHorizontal: 10,
borderRadius: 5,
},
});
export default LoginScreen;
样式优化
替换基础组件为更美观的第三方组件库,如react-native-paper:

import { TextInput, Button, Card } from 'react-native-paper';
// 在return中使用改进后的组件
<Card style={styles.card}>
<Card.Title title="欢迎登录" />
<Card.Content>
<TextInput
label="邮箱"
mode="outlined"
value={email}
onChangeText={setEmail}
/>
<TextInput
label="密码"
mode="outlined"
secureTextEntry
value={password}
onChangeText={setPassword}
/>
<Button mode="contained" onPress={handleLogin}>
登录
</Button>
</Card.Content>
</Card>
表单验证
使用formik和yup实现更强大的表单验证:
import { Formik } from 'formik';
import * as yup from 'yup';
const validationSchema = yup.object().shape({
email: yup.string().email('无效邮箱').required('必填'),
password: yup.string().min(6, '密码太短').required('必填'),
});
<Formik
initialValues={{ email: '', password: '' }}
validationSchema={validationSchema}
onSubmit={values => console.log(values)}
>
{({ handleChange, handleSubmit, errors, touched }) => (
<View>
<TextInput
onChangeText={handleChange('email')}
placeholder="邮箱"
/>
{touched.email && errors.email && <Text>{errors.email}</Text>}
<TextInput
onChangeText={handleChange('password')}
placeholder="密码"
secureTextEntry
/>
{touched.password && errors.password && <Text>{errors.password}</Text>}
<Button onPress={handleSubmit} title="登录" />
</View>
)}
</Formik>
状态管理
集成Redux或Context API管理登录状态:

// 使用React Context示例
const AuthContext = React.createContext();
const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const login = (credentials) => {
// 模拟API调用
return new Promise((resolve) => {
setTimeout(() => {
setUser({ email: credentials.email });
resolve();
}, 1000);
});
};
return (
<AuthContext.Provider value={{ user, login }}>
{children}
</AuthContext.Provider>
);
};
// 在组件中使用
const { login } = useContext(AuthContext);
const handleLogin = async () => {
try {
await login({ email, password });
// 导航到主页
} catch (error) {
Alert.alert('登录失败', error.message);
}
};
导航集成
添加react-navigation实现页面跳转:
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
const Stack = createStackNavigator();
function App() {
return (
<AuthProvider>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Login" component={LoginScreen} />
<Stack.Screen name="Home" component={HomeScreen} />
</Stack.Navigator>
</NavigationContainer>
</AuthProvider>
);
}
安全存储
使用react-native-keychain安全存储凭证:
import * as Keychain from 'react-native-keychain';
const storeCredentials = async (email, password) => {
await Keychain.setGenericPassword(email, password);
};
const getCredentials = async () => {
return await Keychain.getGenericPassword();
};
网络请求
使用axios处理登录API请求:
import axios from 'axios';
const handleLogin = async () => {
try {
const response = await axios.post('https://api.example.com/login', {
email,
password
});
await storeCredentials(email, password);
navigation.navigate('Home');
} catch (error) {
Alert.alert('登录失败', error.response?.data?.message || '网络错误');
}
};






