Как вызвать функцию onChangeText при отображении ее из массива - PullRequest
1 голос
/ 27 сентября 2019

Я использую Array to данные карты , используя карту функции более высокого порядка .И я также использую компонентный ввод InputField , который получает реквизит.но когда я вызываю функцию, она говорит.

Неудачный тип проп: проп onChangeText помечен как необходимый в InputField.но его значение равно undefined.

Поэтому, когда я утешаю адрес электронной почты и пароль, он отображается пустым.

Вот мой код

Вход в систему (экран)

import React, { Component } from "react";
import { StatusBar, View, Text, TouchableOpacity } from "react-native";
import styles from "./styles";
import InputField from "../../components/InputField";

class SignIn extends Component {
  state = {
    email: "",
    password: "",
    textInputData: [
      {
        inputType: "email",
        placeholder: "Enter Email",
        multiline: false,
        autoCorrect: false,
        autoFocus: true,
        onChangeText: this.handleEmailChange
      },
      {
        inputType: "password",
        placeholder: "Enter Password",
        multiline: false,
        autoCorrect: false,
        autoFocus: false,
        onChangeText: this.handlePasswordChange
      }
    ]
  };

  //handle email text input change
  handleEmailChange = email => {
    this.setState({ email: email });
  };

  //handle password text input change
  handlePasswordChange = password => {
    this.setState({ password: password });
  };

  replaceScreen = screen => {
    const { navigate } = this.props.navigation;
    navigate(screen);
  };

  render() {
    return (
      <View style={styles.mainContainer}>
        <StatusBar backgroundColor={"#455A64"} />
        {this.state.textInputData.map((item, index) => {
          return (
            <View key={index} style={styles.inputViewContainer}>
              <InputField
                inputType={item.inputType}
                placeholder={item.placeholder}
                multiline={item.multiline}
                autoCorrect={item.autoCorrect}
                autoFocus={item.autoFocus}
                onChangeText={item.onChangeText}
              />
            </View>
          );
        })}

        <TouchableOpacity
          style={styles.buttonContainerStyle}
          activeOpacity={0.7}
          onPress={() => {
            this.replaceScreen("HomeNavigation");
          }}
        >
          <Text style={styles.buttonTextStyle}>SignIn</Text>
        </TouchableOpacity>

        <View style={styles.bottomContainer}>
          <Text>Don't have an account? </Text>
          <TouchableOpacity
            activeOpacity={0.7}
            onPress={() => {
              this.replaceScreen("SignUp");
            }}
          >
            <Text style={styles.signUpTextStyle}>SignUp</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}
export default SignIn;

InputField (компонент Custome)

import React, { Component } from "react";
import { TextInput, StyleSheet } from "react-native";
import { PropTypes } from "prop-types";

class InputField extends Component {
  constructor(props) {
    super(props);
    this.state = {
      secureInput: !(
        props.inputType === "text" ||
        props.inputType === "email" ||
        props.inputType === "number"
      )
    };
  }

  render() {
    const {
      inputType,
      placeholder,
      multiline,
      autoCorrect,
      autoFocus,
      onChangeText
    } = this.props;
    const { secureInput } = this.state;

    return (
      <TextInput
        inputType={inputType}
        secureTextEntry={secureInput}
        placeholder={placeholder}
        multiline={multiline}
        autoCorrect={autoCorrect}
        autoFocus={autoFocus}
        onChangeText={onChangeText}
        style={styles.textInputStyle}
      />
    );
  }
}

InputField.propTypes = {
  inputType: PropTypes.string.isRequired,
  placeholder: PropTypes.string.isRequired,
  multiline: PropTypes.bool,
  autoCorrect: PropTypes.bool,
  autoFocus: PropTypes.bool,
  onChangeText: PropTypes.func.isRequired
};

const styles = StyleSheet.create({
  textInputStyle: {
    color: "black",
    fontSize: 16
  }
});

export default InputField;

Какрешить это.Я жду вашего решения.И, пожалуйста, дайте мне знать, если я использую правильный путь или нет, чтобы сделать это.Заранее спасибо.

Ответы [ 2 ]

2 голосов
/ 27 сентября 2019

Через несколько часов я решил проблему.Я только изменяю данные onChangeText в состоянии в Экран входа в систему .Без изменений в пользовательском компоненте InputField .Проблема была в том, что я неправильно вызывал метод из состояния.

До

state = {
    email: "",
    password: "",
    textInputData: [
      {
        inputType: "email",
        placeholder: "Enter Email",
        multiline: false,
        autoCorrect: false,
        autoFocus: true,
        onChangeText: this.handleEmailChange
      },
      {
        inputType: "password",
        placeholder: "Enter Password",
        multiline: false,
        autoCorrect: false,
        autoFocus: false,
        onChangeText: this.handlePasswordChange
      }
    ]
  };

После

state = {
    email: "",
    password: "",
    textInputData: [
      {
        inputType: "email",
        placeholder: "Enter Email",
        multiline: true,
        autoCorrect: false,
        autoFocus: true,
        onChangeText: text => this.handleEmailChange(text)
      },
      {
        inputType: "password",
        placeholder: "Enter Password",
        multiline: false,
        autoCorrect: false,
        autoFocus: false,
        onChangeText: text => this.handlePasswordChange(text)
      }
    ]
  };
1 голос
/ 27 сентября 2019

Вы пытаетесь добавить onChangeText из реквизитов. Вы должны использовать реквизиты по умолчанию во время загрузки реквизитов, чтобы они могли полностью удовлетворить ваше требование

InputField.defaultProps = {
   onChangeText: () => {}
}
...