如何在按下按钮时检查文本值,而不是在文本更改时检查文本值?

How can I check the text value when I press on button, rather than whenever text changes?

我放了一个输入和一个按钮。如果我按下按钮时输入的密码正确,我希望它进入主屏幕。但是每当我输入输入时,它都会检查密码是否正确,

我正在使用 React Native Base。

如何解决这个问题?

import React, { useState } from "react";
import { View, StyleSheet, TextInput, Alert } from "react-native";
import { Container, Header, Content, Form, Item, Input, Label, Button, Text } from 'native-base';
const SplashScreen = ({ navigation }) => {
 
  const [password, setPassword] = useState('');
  
  const CORRECT_PASSWORD = "5555";
  const onEnterPin = (password)=>{
      if(password === CORRECT_PASSWORD) {
      
        navigation.navigate("Home");
      }
      else{
        Alert.alert("please check your password")
      }
  };

  return (
    <Container>
      <Header />
      <Content>
        <Form>
          <Item stackedLabel last>
            <Label>Enter Password</Label>
            <Input style={{ borderWidth: .1 }} onChangeText={(text) => setPassword(text)} />
          </Item>
          <Button block onPress={onEnterPin(password)}>
            <Text>Go Home Screen</Text>
          </Button>
        </Form>
      </Content>
    </Container>   
  )
}

export default SplashScreen;

当前每次重新渲染时都会调用该函数。您可以稍微更改函数调用。您也不需要将密码作为参数传递,因为它已经定义为状态。试试这个:

import React, { useState } from "react";
import { View, StyleSheet, TextInput, Alert } from "react-native";
import { Container, Header, Content, Form, Item, Input, Label, Button, Text } from 'native-base';
const SplashScreen = ({ navigation }) => {
 
  const [password, setPassword] = useState('');
  
  const CORRECT_PASSWORD = "5555";
  const onEnterPin = () => {
      if(password === CORRECT_PASSWORD) {
        navigation.navigate("Home");
      }
      else{
        Alert.alert("please check your password")
      }
  };

  return (
    <Container>
      <Header />
      <Content>
        <Form>
          <Item stackedLabel last>
            <Label>Enter Password</Label>
            <Input style={{ borderWidth: .1 }} onChangeText={(text) => setPassword(text)} />
          </Item>
          <Button block onPress={onEnterPin}>
            <Text>Go Home Screen</Text>
          </Button>
        </Form>
      </Content>
    </Container>   
  )
}