ReactNative-无法获取我的const更新

时间:2020-07-31 20:48:56

标签: javascript reactjs react-native

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>
   
  );
}`

1 个答案:

答案 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}