首页 > 解决方案 > React-Native:将变量 onClick 传递给不同文件中的处理程序

问题描述

我是一个新的 React-Native 程序员。我正在尝试创建一个登录页面,但我不确定如何将一些参数传递给位于不同文件中的处理程序函数。

我正在尝试在 onClick() 按钮期间将 SignIn.js 中的变量电子邮件和密码传递给 Auth.js 中的 onVerify

登录.js

import React from "react";
import { View } from "react-native";
import { Card, Button, FormLabel, FormInput } from "react-native-elements";
import { onVerify } from "../auth";
import { onSignIn } from "../auth";


export default class SignIn extends React.Component{
  constructor(props) {
      super(props);
      const {navigation} = this.props.navigation;
      this.state ={
          email : "huzaifah1011@gmail.com",
          password : "12345",
          name : "",
          logged : false
      }
  }


  render(){
    return(
      <View style={{ paddingVertical: 20 }}>
        <Card>
          <FormLabel>Email</FormLabel>
          <FormInput placeholder="Email address..." />
          <FormLabel>Password</FormLabel>
          <FormInput secureTextEntry placeholder="Password..." />

          <Button
            buttonStyle={{ marginTop: 20 }}
            backgroundColor="#03A9F4"
            title="SIGN IN"
            onPress={() => {onVerify(this.state.email,this.state.password);}}
            // {()=> this.onVerify()}

          />
        </Card>
      </View>
    );
  }
}

对于 onClick 函数,即 onVerify 位于 auth.js

import { AsyncStorage } from "react-native";

export const USER_KEY = "auth-demo-key";

export const onSignIn = () => AsyncStorage.setItem(USER_KEY, "true");

export const onSignOut = () => AsyncStorage.removeItem(USER_KEY);

export const onVerify = (email,password) => {
          fetch('xxx',
            {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: 'email=' + this.email + '&password=' + this.password
            })

            .then((response) => response.json())
            .then((responseJson) => {
                if(responseJson.status == '200') {
                    onSignIn();
                    () => navigation.navigate("SignedIn")
                }
                console.log(responseJson)
            })
            .catch((error) => {
                console.error(error);
            });}

标签: javascriptreactjsreact-native

解决方案


SignIn Component 在该函数调用onVerify中添加一个本地函数auth

export default class SignIn extends React.Component{

        //add local function
        onVerify = ()=>{
            onVerify(this.state.email,this.state.password);
        }


      render(){
        return(
          <View style={{ paddingVertical: 20 }}>
            <Card>
              //....
              <Button
                buttonStyle={{ marginTop: 20 }}
                backgroundColor="#03A9F4"
                title="SIGN IN"
                onPress={() => this.onVerify()} //call the local function

              />
            </Card>
          </View>
        );
      }
    }

推荐阅读