我正在尝试开发一个React原生APP。
我对Java和PHP非常有经验,但有些事情让我对react-native感到困惑。
基本上,我试图获得一个工作的登录页面(只是为了实际练习),但当我试图从子组件值(例如,密码输入)传递值到父组件函数(LoginForm)时,我很挣扎。
下面是一个具体的代码:[PasswordInput]
import * as React from 'react';
import { View } from 'react-native';
import { HelperText, TextInput } from 'react-native-paper';
class PasswordInput extends React.Component {
constructor(props){
super(props);
this.state ={
password:''
};
}
getPassword() {
return this.state.password;
}
login(){
alert(this.state.password)
}
OnChangesValue(e){
console.log(e.nativeEvent.text);
this.setState({
userName :e.nativeEvent.text,
})
}
changePassword(e){
console.log(e.nativeEvent.text);
this.setState({
password :e.nativeEvent.text,
})
}
hasErrors(text){
let result=true;
if(text.length>10 || text.length==0){
result=false;
}
return result;
};
render() {
return (
<View>
<TextInput
ref="pass"
name="password"
onChange={this.changePassword.bind(this)}
secureTextEntry={true}
label="Password"
left={<TextInput.Icon name="lock" onPress={() => {
}}/>}
/>
<HelperText type="error" visible={this.hasErrors(this.state.password)}>
Password too short!
</HelperText>
</View>
);
}
}
export default PasswordInput;
字符串
这里是LoginForm组件:
import * as React from 'react';
import { Component, createRef } from "react";
import {View, StyleSheet} from 'react-native';
import {Button, Card, Title} from 'react-native-paper';
import EmailInput from './login_components/email_input';
import PasswordInput from './login_components/password_input';
import {useRef} from 'react/cjs/react.production.min';
class LoginForm extends React.Component {
passwordInput = createRef();
submitForm(){
alert(this.passwordInput['password'].value);
}
render() {
return (
<Card style={styles.detailRowContainer}>
<Card.Title
title="Signup!"
subtitle="Inserisci i tuoi dati per eseguire il login"
/>
<EmailInput/>
<PasswordInput ref={this.passwordInput}/>
<Card.Actions>
<Button mode="contained" type="submit" style={styles.loginButtonSection} onPress={() => this.submitForm()}>
LOGIN
</Button>
</Card.Actions>
</Card>
);
}
}
const styles = StyleSheet.create({
loginButtonSection: {
width: '100%',
height: '30%',
justifyContent: 'center',
alignItems: 'center'
},
detailRowContainer: {
flex:1,
flexDirection:'row',
alignItems:'center',
justifyContent:'center'
},
});
export default LoginForm;
型
我的目标(目前)是了解如何在LoginForm组件中接收PasswordInput值,以便在alert(submitForm()函数)中打印密码。
1条答案
按热度按时间yrdbyhpb1#
也许更容易的是从相反的方向去做,并有一个可重用的组件,它被赋予了改变其外观和功能的 prop 。
登录页面:
字符串
下面是一个Input组件的例子:(因此,我们现在有了一个可重用的组件,它接受接口中定义的一些props,而不是将信息从子组件传递给父组件)。
导入的Input.tsx在文件夹中找到:组件
型
使用“formik”和“yup”是开始登录屏幕的一个很好的方法,它可以快速创建输入字段和使用钩子进行客户端验证。