【问题标题】:Can't focus TextInput when navigating to a screen导航到屏幕时无法聚焦 TextInput
【发布时间】:2021-09-10 21:55:02
【问题描述】:

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

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

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

【问题讨论】:

    标签: reactjs react-native react-hooks react-navigation react-native-paper


    【解决方案1】:

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

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

    我测试了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 毫秒

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

    【讨论】:

    • 我试过这个,现在有时会聚焦,但有时似乎聚焦然后立即失焦......
    • 如果您可以添加更多代码或创建带有问题的零食,请这样做。
    • 嗯,我在这里重写了代码:snack.expo.dev/@pta2002/0745da,现在它可以工作了......我想我就用这个
    • 我真的不知道为什么它不起作用,我将此代码复制粘贴到我的应用程序中,但它仍然不起作用。我想它一定是其他地方的东西
    • 更新:我再次尝试了同样的博览会,但这次没有成功,所以我想这里还是有问题。似乎这只是在android版本上发生的事情。
    猜你喜欢
    • 2020-05-31
    • 2018-12-30
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多