导航到屏幕时无法聚焦 TextInput

Can't focus TextInput when navigating to a screen

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

在另一次尝试中,我尝试通过监听屏幕上的 'focus' 事件来手动聚焦它,但这只是在我第一次打开屏幕时聚焦它。有什么办法让它可靠地工作吗?

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>
  )
}

使用 React.useRef() 而不是 createRef();
ref定义为可以使用时,使用React.useEffect监听。

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 评论

I tried this, and it focuses sometimes now, but sometimes it seems to focus and then immediatelly unfocus...

我测试了 snack,正如他所说,它有时已经无法正常工作了!
真的我不明白为什么?但我尝试了一些东西,它起作用了。

transitionEnd 而不是 focus

尝尝小吃here

  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])