将 Input 值传递给父组件函数

Pass Input value to parent component function

我正在尝试开发一个react-native APP。 我对 Java 和 PHP 非常有经验,但有些东西让我对 react-native 感到困惑。 基本上,我试图获得一个有效的登录页面(仅用于实际练习),但是当我尝试将值从子组件值(例如,密码输入)传递到父组件函数(LoginForm)时,我遇到了困难。 下面是具体的代码: [密码输入]

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 值,以便在警报(submitForm() 函数)中打印密码。

也许更容易的做法是朝相反的方向去做,并拥有一个可重用的组件,该组件被赋予道具以改变其外观和功能:

着陆页:

// importing Input.tsx from folder: components
import Input from '../components/Input';

export default function LandingScreen() {
  // Hooks for email and password
  const [email, set_email] = useState<string>('');
  const [password, set_password] = useState<string>('');

return(
       <View>
            <Input
              placeholder="Email"
              onChangeText={(text) => set_email(text)}
              keyboardType="email-address"
            />
            <Input
              placeholder="Password"
              onChangeText={(text) => set_password(text)}
              secureTextEntry={true}
              keyboardType="default"
            />
       </View>
)

这里是输入组件的示例: (所以我们现在有一个可重用的组件,它接受在其接口中定义的一些道具,而不是将信息从 child 传递到 parent)

已导入 Input.tsx 在文件夹中找到:components

import React, { FC } from 'react';
import { View, StyleSheet, useWindowDimensions } from 'react-native';
import { TextInput } from 'react-native-gesture-handler';

interface Props {
  placeholder: string;
  onChangeText: (text: string) => void;
  secureTextEntry?: boolean;
  keyboardType: any;
}

const Input: FC<Props> = (props) => {
  const { width } = useWindowDimensions();
  return (
    <View style={styles.container}>
      <TextInput
        style={[styles.input, { width: width * 0.8 }]}
        autoCapitalize={'none'}
        placeholder={props.placeholder}
        secureTextEntry={props.secureTextEntry}
        onChangeText={props.onChangeText}
        keyboardType={props.keyboardType}
        placeholderTextColor={'black'}
      />
    </View>
  );
};

export default Input;

const styles = StyleSheet.create({
  container: {
    alignSelf: 'center',
    backgroundColor: '#e3e3e3',
    borderRadius: 5,
    marginVertical: 10,
  },
  input: {
    padding: 15,
  },
});

开始使用登录屏幕的一个好方法是使用“formik”和“yup”,它可以快速创建输入字段并 client-side 使用挂钩进行验证。