如何在React Native中自动打开键盘?

37

我在我的React Native应用程序中有一个屏幕,其中有几个文本字段。

我想知道是否有任何方法,在屏幕加载时我的光标自动打开并聚焦于我的第一个文本输入字段?

我正在寻找类似于Android中的stateAlwaysVisible的东西。

9个回答

50

<TextInput />聚焦时,键盘应该自动打开。您可以使用autoFocus属性使其在元素挂载时获得焦点(链接


36
当页面通过堆栈导航加载时,“autoFocus”似乎不起作用。它会将焦点放在“textInput”上,但不会打开键盘。 - SoundStage
32
用参考方式手动对焦不会触发键盘。虽然有Keyboard.dismiss(),但React Native文档中没有show()。 - Dan
5
@Dan,我这里也遇到了同样的问题。想通过引用来聚焦一个TextInput并打开键盘。你找到任何解决方案了吗? - Dror Bar
5
这个回答并没有回答问题,而是提供了一个特定情况下的解决方法。如果某人不想/不能使用自动对焦,那么这个答案就不适用。当聚焦时键盘不显示。 - Jaqueline Passos
1
可以确认,在使用堆栈导航时,autoFocus 在安卓设备上有效。 - user1462498
显示剩余4条评论

20

这个技巧对我起作用了

setTimeout(() => InputRef.current.focus(), 100)

谢谢这个。对我来说非常有效。 - Uéslei Suptitz

17

我的方式(在组件渲染时出现聚焦和显示键盘的问题)

import { InteractionManager, TextInput } from 'react-native';

...

inputRef = React.createRef();

componentDidMount() {
  this.focusInputWithKeyboard()
}

focusInputWithKeyboard() {
  InteractionManager.runAfterInteractions(() => {
    this.inputRef.current.focus()
  });
}

render() {
  <TextInput ref={this.inputRef} />
}

11

另一种解决方案 :)

import React, { useRef } from 'react'

export function mycomponent(props) {
   const inputRef = useRef();
   
   return(
         <TextInput 
           ref={inputRef}
           onLayout={()=> inputRef.current.focus()}>
         </TextInput>
   )
}


2
这是最好的答案,它可以完美地工作!如果您想要在模态框中聚焦输入,请使用 Modal 的 onShow 事件而不是 TextInput 的 onLayout,它将无缝地工作。 <Modal visible={visible} onShow={() => inputRef.current?.focus()}/><TextInput ref={inputRef} /></Modal> - malko
当返回到该屏幕时,onLayout没有被调用! - Cagri Uysal

1

对我来说有效。

<TextInput
        autoFocus={false}
        autoCapitalize="none"
        onChangeText={(val) => {
            props.onChange(val);
        }}
        value={null}
        defaultValue={props.defaultValue}
        ref={(ref) => {

            if( ref !== undefined && ref && !ref.isFocused() ){

                ref.focus();
            }
        }}
        {...propsMerge}
    />

0
这是使用setTimeout()钩子的代码示例:
import { StyleSheet, Text, View, TextInput } from "react-native";
import React from "react";

const HomeScreen = () => {
  const inputRef = React.useRef();

  setTimeout(() => inputRef.current.focus(), 100);
  return (
    <View style={{ paddingVertical: 20 }}>
      <Text>circle</Text>
      <TextInput ref={inputRef} />
    </View>
  );
};

export default HomeScreen;

const styles = StyleSheet.create({});

2
setTimeOutuseEffect 包装起来,否则它会在每次渲染时都被创建! - Cagri Uysal
只是为了澄清一些事情: 1)setTimeout不是一个钩子,它只是一个JS函数。 2)你需要用useEffect钩子包装它,就像之前说的那样。 3)当组件卸载时,最好取消它(在useEffect的最后返回一个清理函数),像下面这样:useEffect(() => { const timeout = setTimeout(() => inputRef.current.focus(), 100); return () => { clearTimeout(timeout) } }, []) - undefined

0

这在我的模拟器上似乎可以工作。尚未在真实设备上确认。

constructor(props) {
  super(props);
  this.buildNameTextInput = React.createRef();
}

<TouchableOpacity
  style={styles.mainButton}
  onPress={() => {
    this.buildNameTextInput = true
    this.props.setSaveBuildModal(true)
  }}
>
  <Text style={styles.mainButtonText}> Save Build </Text>
</TouchableOpacity>

<TextInput
  autoFocus={!!this.buildNameTextInput}
  ref={this.buildNameTextInput}
  placeholder="Type a Name"
  autoCapitalize="words"
  style={{...styles.heroBtnText, marginVertical: 50}}
  onChangeText={buildName => this.props.setCurrentBuildName(buildName)}
  value={this.props.buildName}
/>
  1. 我需要构造函数来注册引用
  2. 处理程序将本地变量设置为true
  3. autoFocus将触发字段聚焦。键盘有时会在Android模拟器上打开(这一点我无法解释)。
  4. ref是对DOM元素的引用

0

你可以将 TextInput 的引用存储为textInputRef,然后使用 this.textInputRef.focus()。


-1

由于堆栈导航的问题(请参见所选解决方案上“SoundStage”的评论),所选解决方案对我无效。

我添加了一个名为openTheKeyboard的新变量,最初将其设置为false

我的临时解决方案:

componentDidMount() {
  this.setState({ openTheKeyboard: true });
}

componentDidUpdate() {
  if (this.state.openTheKeyboard) {
    this.textInput.focus();
    this.setState({ openTheKeyboard: false });
  }
}

5
如果在调用 .focus() 时键盘没有显示出来,可能的原因是什么? - Mayoul
应该将this.textInput.focus(); 改为 this.textInput.current.focus(); - showtime

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接