React-Native:Formik引用无法获得价值 [英] React-Native: Formik ref fails to get value

查看:48
本文介绍了React-Native:Formik引用无法获得价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以react-native形式使用formik形式的虚拟登录代码

I have a dummy Login code with formik form in react-native

import React, { Component } from "react";
import {
  TextInput,
  Text,
  Alert,
  Image,
  View,
  TouchableOpacity,
  SafeAreaView,
  ScrollView
} from "react-native";
import styles from "./Styles/LoginStylesheet";
import { KeyboardAccessoryNavigation } from "react-native-keyboard-accessory";
import { Formik } from "formik";
import schemaObject, { initialValues, refs } from "./Validations/LoginValidations";

export default class LoginView extends Component {

  constructor(props) {
    super(props);
    this.state = {
      activeInputIndex: 0
    };
  }

  handleFocus = index => () => {
    this.setState({
      activeInputIndex: index
    });
  };

  handleFocusNext = () => {
    if (this.state.activeInputIndex + 1 >= refs.length) {
      return;
    }
    refs[this.state.activeInputIndex + 1].focus();
  };

  handleFocusPrevious = () => {
    if (this.state.activeInputIndex - 1 < 0) {
      return;
    }
    refs[this.state.activeInputIndex - 1].focus();
  };

  handleLogin = () => {
    console.log("ACTIOn");
      // this.formik.handleSubmit();
  };

  render() {
    return (
      <View style={styles.safeAreaView}>
        <SafeAreaView style={styles.safeAreaView}>
          <ScrollView style={styles.superView}>
            <Formik {/* LINE 56  */}
              initialValues={initialValues}
              onSubmit={values => Alert.alert(JSON.stringify(values))}
              validationSchema={schemaObject}
              ref={p => (this.formik = p)}
            >
              {({
                values,
                handleChange,
                errors,
                setFieldTouched,
                touched,
                isValid,
                handleSubmit
              }) => (
                <View style={styles.superView}>
                  <View style={styles.logoParentView}>
                    <Image
                      source={require("../../Resources/Assets/Login/aptihealth_logo.png")}
                      resizeMode={"contain"}
                      style={styles.logo}
                    />
                  </View>

                  <View style={styles.emailParentView}>
                    <Text style={styles.titleLabel}>Email Id</Text>
                    <TextInput
                      value={values.emailId}
                      onChangeText={handleChange("emailId")}
                      onBlur={() => setFieldTouched("emailId")}
                      placeholder="Email Id"
                      style={styles.textInput}
                      autoCorrect={false}
                      onFocus={this.handleFocus(0)}
                      ref={input => {
                        refs[0] = input;
                      }}
                    />
                    {touched.emailId && errors.emailId && (
                      <Text style={{ fontSize: 10, color: "red" }}>
                        {errors.emailId}
                      </Text>
                    )}
                  </View>

                  <View style={styles.passwordParentView}>
                    <Text style={styles.titleLabel}>Password</Text>
                    <TextInput
                      value={values.password}
                      onChangeText={handleChange("password")}
                      placeholder="Password"
                      onBlur={() => setFieldTouched("password")}
                      style={styles.textInput}
                      autoCorrect={false}
                      secureTextEntry={true}
                      onFocus={this.handleFocus(1)}
                      ref={input => {
                        refs[1] = input;
                      }}
                    />
                    {touched.password && errors.password && (
                      <Text style={{ fontSize: 10, color: "red" }}>
                        {errors.password}
                      </Text>
                    )}
                  </View>

                  <View style={styles.forgotPasswordParentView}>
                    <TouchableOpacity
                      style={styles.forgotpasswordButton}
                      activeOpacity={0.7}
                    >
                      <Text>Forgot Password?</Text>
                    </TouchableOpacity>
                  </View>

                  <View style={styles.loginParentView}>
                    <TouchableOpacity
                      onPress={() => {
                        console.log("VALUES: ", values, this.formik);
                        this.handleLogin();
                      }}
                      style={styles.loginButton}
                      activeOpacity={0.7}
                    >
                      <Text style={styles.loginText}>Login</Text>
                    </TouchableOpacity>
                  </View>

                  <View style={styles.seperaterParentView}>
                    <View style={styles.seperaterView} />
                    <Text style={styles.seperaterText}>OR</Text>
                    <View style={styles.seperaterView} />
                  </View>

                  <View style={styles.faceIdLoginParentView}>
                    <Image
                      source={require("../../Resources/Assets/face_id_small_color/face_id_small_color.png")}
                      resizeMode={"contain"}
                    />
                    <TouchableOpacity style={styles.faceIdButton}>
                      <Text>Sign In with Face ID</Text>
                    </TouchableOpacity>
                  </View>
                  <View style={styles.signUpParentView}>
                    <TouchableOpacity style={styles.signupButton}>
                      <Text>Sign Up for Account Here</Text>
                    </TouchableOpacity>
                  </View>
                </View>
              )}
            </Formik>
          </ScrollView>
        </SafeAreaView>
        <KeyboardAccessoryNavigation
          nextDisabled={false}
          previousDisabled={false}
          nextHidden={false}
          previousHidden={false}
          onNext={this.handleFocusNext}
          onPrevious={this.handleFocusPrevious}
          avoidKeyboard
        />
      </View>
    );
  }
}

我正在尝试在登录操作中控制台formik ref并获得带有调试错误的未定义值

I am trying to console formik ref in login action getting undefined value with debug error

ExceptionsManager.js:126 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Check the render method of `LoginView`.
    in Formik (at LoginView.js:56)

我不知道为什么它变得不确定?

I have no idea why it's getting undefined ??

推荐答案

您应该看看这个问题.

您的问题在这里

<Formik
  initialValues={initialValues}
  onSubmit={values => Alert.alert(JSON.stringify(values))}
  validationSchema={schemaObject}
  ref={p => (this.formik = p)} {/* passing this ref will throw the error */}
>

在最新版本的Formik中,他们按照问题中的说明将Formik更改为功能组件,如果您通过ref,则会出现此错误.

In the latest version of Formik, they changed Formik to a functional component as explained in the issue, which gives you this error if you pass ref's.

您可以检查有关该问题的建议,或者等待它们发布包含更正的更新.

You can check for the suggestions on the issue or wait until they release an update with the correction.

Formik进行了更新,现在您可以将ref与道具 innerRef 一起使用.

Formik made an update and now you can use ref with the prop innerRef.

请参阅此评论

您应该将其更改为

<Formik
  initialValues={initialValues}
  onSubmit={values => Alert.alert(JSON.stringify(values))}
  validationSchema={schemaObject}
  {/* using innerRef instead of ref*/}
  innerRef={p => (this.formik = p)} {/* this will give you the formik bag */}
>

这样,您就可以按自己的意愿调用 this.formik.handleSubmit().

And this way you can call this.formik.handleSubmit(), just lik you want to do.

这篇关于React-Native:Formik引用无法获得价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆