我正在使用 React Native 构建一个 Android 应用程序。
如何强制 TextInput
为“unFocus”,这意味着光标在文本字段内闪烁。有 isFocused()
和 onFocus()
的功能,但我实际上如何让文本字段放弃焦点。您会认为一旦我按 Enter 键,它就会自动执行此操作,但事实并非如此。
import React, {Component} from 'react';
import { AppRegistry, Text, View, StyleSheet, TextInput, TouchableOpacity}
from 'react-native';
var SHA256 = require("crypto-js/sha256");
export default class LoginForm extends Component{
constructor(props){
super(props);
this.state = {
email: '',
password:''
};
}
tryLogin = () => {
if(this.state.email=="email123" && this.state.password == "password"){
console.log("password verified");
this.props.navigator.replace({
title: 'Dashboard'
});
}
console.log(this.state.email);
console.log(this.state.password);
console.log("Hash" + SHA256(this.state.password));
}
render(){
return(
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder="Email address"
placeholderTextColor="white"
onChangeText={(email) => this.setState({email})}>
</TextInput>
<TextInput style={styles.input}
placeholder="Password"
placeholderTextColor="white"
secureTextEntry
onChangeText={(password) => this.setState({password})}>
</TextInput>
<TouchableOpacity style={styles.loginButtonContainer} onPress={this.tryLogin}>
<Text style={styles.loginButtonText}>LOGIN</Text>
</TouchableOpacity>
</View>
);
}
}
AppRegistry.registerComponent('LoginForm', () => LoginForm);
const styles = StyleSheet.create({
container: {
padding: 20
},
input:{
height: 40,
backgroundColor: '#e74c3c',
marginBottom: 20,
color: 'white',
paddingHorizontal: 15,
opacity: .9
},
loginButtonContainer:{
justifyContent: 'center',
backgroundColor: '#bc4c3c',
paddingVertical:15
},
loginButtonText:{
textAlign:'center',
color:'white',
fontWeight: '700',
fontSize: 24
}
})
对于真实用户来说,这可能并不重要,但我只是在模拟,如果我想重新加载它会很讨厌。
原文由 Noah Mendoza 发布,翻译遵循 CC BY-SA 4.0 许可协议
更好的方法是使用 ScrollView 和 Keyboard.dismiss 。通过在用户在 textInput 之外点击时使用 ScrollView ,键盘被解除。这样做是因为 ScrollView 的默认属性 keyboardShouldPersistTaps 是 never 。这是用户期望的行为。为了关闭键盘,或者等效地模糊 textInput ,当用户点击登录按钮时,将 Keyboard.dismissed() 添加到 tryLogin 函数。