首页 > 解决方案 > 导航到屏幕时无法聚焦 TextInput

问题描述

我有一个 react-native-paper TextInput,我想在导航到屏幕时自动聚焦(使用 react-native-navigation)。我已经尝试autoFocus={true}在 TextInput 上进行设置,但没有奏效。

在另一次尝试中,我尝试通过收听屏幕上的“焦点”事件来手动对焦,但这只是在我第一次打开屏幕时才对焦。有没有办法让它可靠地工作?

export default function NewAccountScreen({ navigation }) {
  const [name, setName] = useState('');

  const textInputRef = createRef();

  // This isn't working, neither is autoFocus...
  const focusOnInput = () => {
    textInputRef.current?.focus();
  }

  navigation.addListener("focus", focusOnInput);

  return (
    <View>
      <TextInput ref={textInputRef} label="Account name" value={name} onChangeText={setName}/>
    </View>
  )
}

标签: reactjsreact-nativereact-hooksreact-navigationreact-native-paper

解决方案


使用React.useRef()而不是 createRef();
use React.useEffectto listenref被定义为可以使用它。

export default function NewAccountScreen({ navigation }) {
  const [name, setName] = useState('');

  const textInputRef = React.useRef();

  React.useEffect(() => {
     if(textInputRef.current){
        const unsubscribe = navigation.addListener('focus', () => {
          textInputRef.current?.focus()
        });
       return unsubscribe;
     }
  }, [navigation, textInputRef.current]);

  return (
    <View>
      <TextInput ref={textInputRef} label="Account name" value={name} onChangeText={setName}/>
    </View>
  )
}

更新:如@pta2002 评论

我试过这个,它现在有时会聚焦,但有时它似乎聚焦然后立即失焦......

我测试了零食,正如他所说,它在某些时候已经不起作用了!
真的我不明白为什么?但我尝试了一些东西,它是工作。

听不听transitionEnd_focus

试试这里的小吃

  React.useEffect(() => {
    if (textInputRef.current) {
      const unsubscribe = navigation.addListener('transitionEnd', () => {
        textInputRef.current?.focus();
      })

      return unsubscribe;
    }
  }, [navigation, textInputRef.current])

其他解决方案适用于我textInputRef.current?.focus();的 setTimeout 和 1000 ms

  React.useEffect(() => {
    if (textInputRef.current) {
      const unsubscribe = navigation.addListener('focus', () => {
        setTimeout(() => {
           textInputRef.current?.focus();
        }, 1000);
      })

      return unsubscribe;
    }
  }, [navigation, textInputRef.current])

推荐阅读