首页 > 解决方案 > 在 React Native 中提交表单时处理键盘事件?

问题描述

我创建了一个登录表单,每当我点击输入框时,键盘就会打开,但是当我按下提交按钮时,键盘会先关闭,然后我再次按下提交按钮,然后表单就会提交。但我希望每当我点击提交按钮时,键盘会自动关闭,并且表单会同时提交。

import React, { Component } from "react";
import { View, Text, Button,KeyboardAvoidingView } from "react-native";
import { Button, Input } from "native-base";

export default class TestForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      email: "",
      password: "",
    };
  }

  handleSignupChange = (data, text) => {
    this.setState({ [data]: text });
  };

  submitForm = () => {
      const {email,password}=this.state;
      console.log('form value',email,password);
  };
  render() {
    return (
      <KeyboardAvoidingView enabled={true}>
        <Text> TestForm </Text>
        <Input
          onChangeText={(e) => this.handleSignupChange("email", e)}
          placeholder="email"
        />
        <Input
          onChangeText={(e) => this.handleSignupChange("password", e)}
          placeholder="password"
        />
        <Button onPress={this.submitForm} />
      </KeyboardAvoidingView>
    );
  }
}

标签: javascriptreactjsreact-native

解决方案


尝试这个:

您导入Keyboardfromreact-native并在函数开头调用它以隐藏键盘

import { Keyboard } from 'react-native';

submitForm = () => {
 Keyboard.dismiss
 const {email,password}=this.state;
 console.log('form value',email,password);
};

推荐阅读