使用TabNavigator时,React Navigation autoFocus

时间:2017-08-21 17:29:03

标签: react-native react-navigation

在反应导航中,处理具有自动聚焦输入的表单的选项卡的最佳方法是什么,该表单会自动拉出键盘?

当导航器初始化所有屏幕时,即使没有autoFocus元素的屏幕首先显示,它也会自动显示键盘。

当我在带有表单的选项卡上时,我想让它打开键盘,但是当我离开那个视图时关闭它。

以下是一个示例(和an associated Gist):

App.js

const AppNavigator = TabNavigator( {
  listView: { screen: TheListView },
  formView: { screen: TheFormView }
} )

TheFormView.js

const TheFormView = () => {
  return (
    <View style={{ marginTop: 50 }}>
      <TextInput
        autoFocus={ true }
        keyboardType="default"
        placeholder="Blah"
      />
    </View>
  )
}

TheListView.js

const TheListView = () => {
  return (
    <View style={{ marginTop: 50 }}>
      <Text>ListView</Text>
    </View>
  )
}

2 个答案:

答案 0 :(得分:0)

您应该在TabNavigator配置上使用lazyhttps://github.com/react-community/react-navigation/blob/master/docs/api/navigators/TabNavigator.md#tabnavigatorconfig

这可以防止屏幕在被查看之前被初始化。

还要考虑进行某种状态管理或查找自定义导航器(https://reactnavigation.org/docs/navigators/custom),以便仅在导航到 TheFormView 时将autoFocus道具设置为true。

答案 1 :(得分:0)

This answer到2020年4月对我来说已经过时了,但这对我有用:

import { useFocusEffect, } from "@react-navigation/native"
import React, { useEffect, useState, } from "react"
...
const CreateProfileScreen = ({ navigation, }) => {
   const [safeToOpenKeyboard, setSafeToOpenKeyBoard] = useState(false)
   ...
   useFocusEffect(
        React.useCallback(() => {
            console.log("Navigated to CreateProfileScreen")
            setSafeToOpenKeyBoard(true)
            return () => {
                console.log("Navigated away from CreateProfileScreen")
                setSafeToOpenKeyBoard(false)
            }
        }, [])
    )
   ...
   return (<TextInput autoFocus={safeToOpenKeyboard}/>)
}