React Native TextInput 自动获取焦点功能无效。

3

我在React Native应用程序中有两个屏幕,称为屏幕A和屏幕B。屏幕A中有一个文本输入框。我为此设置了自动聚焦并且最初它可以正常工作。

当我们从屏幕A导航到屏幕B,然后再从B->A导航回来时,文本输入框的自动聚焦功能无法正常工作。

是否有人有解决方法?

<TextInput
  style={styles.textInput}
  textStyle={styles.inputTextStyle}
  autoFocus={true}
  placeholder='Enter Code'
  keyboard={'numeric'}
  placeholderTextColor={AppStyles.color.grey}
  value={code}
  onChangeText={this.updateCode}
  underline={false}
/>

1
这个链接可能有所帮助:https://reactnavigation.org/docs/navigation-lifecycle/。对于想知道如何监听屏幕从B返回到A的人,可以使用`useFocusEffect`钩子。 - Jarrett
3个回答

3

这是因为 autofocus 首次在 componentDidMount 上触发。要在从 B 返回到 A 后手动触发它,您必须使用 withNavigationFocus HOC。因此,当用户关注屏幕 A 时,您可以使用以下代码显示键盘。

import React from 'react';
import { Text } from 'react-native';
import { withNavigationFocus } from 'react-navigation';

class FocusStateLabel extends React.Component {
   componentDidUpdate() {
       if(this.props.isFocused){
           this.inputField.focus();
       }
   }  
   render() {
     return (
       <TextInput
         ref={(input) => { this.inputField = input; }}
         placeholder = "inputField"
       />
     )
  }
}

// withNavigationFocus returns a component that wraps FocusStateLabel and passes
// in the navigation prop
export default withNavigationFocus(FocusStateLabel);

1
AutoFocus属性仅在组件挂载时触发。当您返回到A时,如果A仍然挂载(只是隐藏),则自动对焦将不会再次起作用。
您应该使用Ref(例如,在此处添加一个新的状态ref),并添加处理程序,在从B导航回A时,触发this.state.ref.focus()
<TextInput
          ref={ref => ref && this.setState({ref})}
          style={styles.textInput}
          textStyle={styles.inputTextStyle}
          autoFocus={true}
          placeholder='Enter Code'
          keyboard={'numeric'}
          placeholderTextColor={AppStyles.color.grey}
          value={code}
          onChangeText={this.updateCode}
          underline={false}
        />

0

根据Jarret的评论(withNavigationFocus在V6中已被弃用)和这个StackOverflow答案(当导航到屏幕时无法聚焦TextInput):

import {useFocusEffect} from 'react-navigation/native';

const TestFocus = (props) => {

  const textRef = useRef(null);

  useFocusEffect(
    useCallback(() => {
     // When the screen is focused
     const focus = () => {
      setTimeout(() => {
       textRef?.current?.focus();
      }, 1);
     };
     focus();
     return focus; // cleanup
    }, []),
  );


  return (
   <TextInput
     ref={textRef}
   />
  )
  
}

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