javascript - 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);
});}
解决方案
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>
);
}
}
推荐阅读
- spring-data-jpa - h2数据库的“列数不匹配”使用Spring-Boot @DataJpaTest中的投影选择查询
- vba - 设置停靠在主窗口中的电子邮件的 MailItem.Sensitivity
- webpack - 收到'错误:无法解决
' 尝试在本地使用自定义构建的模块时 - javascript - 在掷骰子事件侦听器中,如何将警报延迟到新骰子图像加载后?
- python-3.x - 使用 Python3 解析附加的 .MSG 文件
- javascript - 仅当元素在屏幕上时才运行 Jquery 代码
- javascript - 递归不适用于多个级别
- c# - 抛出异常:使用 TransactionScope 时 mscorlib.dll 中的“System.UnauthorizedAccessException”
- google-bigquery - 迁移到聚簇表
- coq - 为什么 Coq 反对以下 PairUsualDecidableTypeFull 模块类型?