【问题标题】:Persist keyboard when showing a React Native modal显示 React Native 模式时保持键盘
【发布时间】:2020-08-22 14:00:26
【问题描述】:

我想在用户点击按钮时显示模式,而不关闭键盘。不幸的是,模式一出现,键盘就会消失。

最小复制案例:

import * as React from "react";
import { Button, Modal, Text, TextInput, View } from "react-native";

function TestComp() {
    const [showingModal, setshowingModal] = React.useState(false);
    return (
        <View style={{ flex: 1, justifyContent: "center", alignItems: "center", marginTop: 22 }}>

            <Modal visible={showingModal} transparent onRequestClose={() => setshowingModal(false)}>
                <View style={{ flex: 1, marginTop: 22 }}>
                    <Button title={"hide modal"} onPress={() => setshowingModal(false)} />
                </View>
            </Modal>

            <TextInput placeholder="Focus to show keyboard" />
            <Button title={"Show modal"} onPress={() => setshowingModal(true)} />
        </View>
    );
}

仅供参考,我正在使用博览会。

如何强制键盘保持不变?

【问题讨论】:

  • 当您点击TextInput 时,键盘会打开,从而获得焦点;当您点击按钮以显示模式时,TextInput 失去焦点,因此键盘关闭。打开 modal 时,你想在哪里设置键盘焦点?
  • @ChristosLytras,按下按钮不会移除键盘上的焦点(例如,我可以在onPress 中放置console.log)。消除焦点的是专门显示的模态。

标签: react-native expo react-native-modal


【解决方案1】:

您可以使用属性autoFocus 在模态框内添加一个隐藏的TextInput,这是一个非常简单的解决方法,当您按下按钮并且模态框显示时,焦点将转到隐藏的输入,保持键盘打开

https://snack.expo.io/Q01r_WD2A

import * as React from 'react';
import {Button,Modal,Text,TextInput,View,Keyboard,ScrollView} from 'react-native';

export default function TestComp() {
  const [showingModal, setshowingModal] = React.useState(false);

  return (
    <View style={{ flex: 1, justifyContent: "center", alignItems: "center", marginTop: 22 }}>
      <Modal
        visible={showingModal}
        transparent
        onRequestClose={() => setshowingModal(false)}>
        <View style={{ flex: 1, marginTop: 22 }}>
          <TextInput autoFocus={true} placeholder="Autofocus to keep the keyboard" style={{display: 'none'}} />
          <Button title={'hide modal'} onPress={() => setshowingModal(false)} />
        </View>
      </Modal>

      <TextInput placeholder="Focus to show keyboard" />
      <Button title={'Show modal'} onPress={() => setshowingModal(true)} />
    </View>
  );
}

【讨论】:

  • autofocus 在显示为无时似乎不起作用。即使我找到其他解决方案来隐藏它(不透明度:0),它也会导致键盘隐藏然后再次出现。当我隐藏模式时,它还迫使我找到并重新关注以前的输入。
猜你喜欢
  • 1970-01-01
  • 2016-12-23
  • 2019-09-15
  • 2020-10-23
  • 2015-04-18
  • 1970-01-01
  • 2015-04-18
  • 1970-01-01
  • 2020-03-15
相关资源
最近更新 更多