导航到屏幕时无法聚焦 TextInput

pta*_*002 2 reactjs react-native react-navigation react-hooks react-native-paper

我有一个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>
  )
}
Run Code Online (Sandbox Code Playgroud)

Ahm*_*ber 6

使用React.useRef()而不是createRef();
use React.useEffectto Listen 当ref定义为可以使用它时。

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>
  )
}
Run Code Online (Sandbox Code Playgroud)

更新:作为@pta2002评论

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

我测试了这种零食,正如他所说,它有时已经不起作用了!
我真的不明白为什么?但我尝试了一些东西,它成功了。

transitionEndfocus

尝试这里的小吃

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

      return unsubscribe;
    }
  }, [navigation, textInputRef.current])
Run Code Online (Sandbox Code Playgroud)

其他解决方案对我来说适用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])
Run Code Online (Sandbox Code Playgroud)