im试图使用onChangeText
修改我的const值,但它始终返回“未定义”。
import { StyleSheet, Text, View, KeyboardAvoidingView, Image, TextInput, TouchableOpacity, alert, Alert } from 'react-native';
export default function App() {
const [user, setUser] = useState(' ');
login = (user) => {
Alert.alert("Bem vindo, " + user, "Login realizado!")
}
return (
<KeyboardAvoidingView style={styles.background}>
<View style={styles.containerLogo}>
<Image
source={require('./src/logo.png')}
style= {{width: 300, height: 300}}
/>
</View>
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder="Usuário"
autoCorrect={false}
onChangeText = {(user) => setUser(user)}
/>
<TextInput
style={styles.input}
secureTextEntry={true}
placeholder="Senha"
autoCorrect={false}
onChangeText={()=>{}}
/>
<TouchableOpacity
style={styles.button}
onPress={ () => {login()}}
>
<Text style={styles.buttonText}>
Entrar
</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
);
}`
答案 0 :(得分:1)
它是未定义的,因为login
被定义为接受user
自变量。您不会在回调中传递任何值,因此未定义局部函数变量user
。
您需要将user
传递给login
函数。
login = user => {
Alert.alert("Bem vindo, " + user, "Login realizado!") // <-- local scope user
}
...
onPress={() => login(user)} // <-- user state object
或者让login
简单地消耗功能组件主体范围内的user
状态。
login = () => {
Alert.alert("Bem vindo, " + user, "Login realizado!") // <-- user state object
}
...
onPress={login}