😺

react-nativeでキーボード入力をさせる際に、画面外でフォーカスをあててもキーボードが閉じられない

2024/01/21に公開

背景

react-native-elementsでreact-hook-formを使用して、Inputタグを使い、キーボードを入力しようとフォーカスを当てて開いた際に、キーボードの外をクリックして、消そうとしても表示されたままになる

修正前のソース

	    <Controller
              control={control}
              rules={{ required: true }}
              render={({ field: { onChange, onBlur, value } }) => (
                <Input
                  placeholder="パスワード"
                  onBlur={onBlur}
                  onChangeText={onChange}
                  value={value}
                  containerStyle={otherStyles.normalInput}
                />
              )}
              name="password"
            />

結論

以下の修正を加える

import React, { ReactNode } from 'react';
import {
  KeyboardAvoidingView,
  TouchableWithoutFeedback,
  Keyboard,
  Platform,
  View,
} from 'react-native';

import keyboardStyles from './layout';

interface KeyboardAvoidingWrapperProps {
  children: ReactNode;
}

export const KeyboardAvoidingWrapper = ({
  children,
}: KeyboardAvoidingWrapperProps) => {
  return (
    <KeyboardAvoidingView
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      style={keyboardStyles.container}>
      <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
        <View style={keyboardStyles.touchableWithoutFeedback}>{children}</View>
      </TouchableWithoutFeedback>
    </KeyboardAvoidingView>
  );
};

export default KeyboardAvoidingWrapper;

上記のファイルをコンポーネントの上位(SafeAreaView)の上あたりに、配置してラップすることで、修正対応可能

KeyboardAvoidingViewとTouchableWithoutFeedbackでラップすることが重要なため、キーボード入力がある画面だけ実装すれば良い。

Discussion