简体   繁体   中英

How do I refocus a <TextInput> after an event?

When the screen loads, I use the following code to focus on a:

useEffect(() => {
  InteractionManager.runAfterInteractions(() => {
    if (refText.current) {
      refText.current.focus();
    }
  });
}, []);

This works as expected. However, on a submit event, the needs focus again.

function myEvent() {
  if (refText.current) {
    refText.current.focus();
  }
}

This does not focus on the text again. Any ideas?

Actually, i don't know why you'd need a if statement inside your submit handler to set the focus on the TextInput , but anyways, I presume you have a event handler on your Button declaration. Eg:

function App() {
  const textRef = useRef();

  const handleSubmit = () => {
    if (textRef.current) textRef.current.focus();
  };

  return (
    <View>
      <TextInput placeholder="Input" ref={textRef}/>
      <Button title="Submit" onPress={handleSubmit} />
    </View>
  );
}
});

It works fine as you can see in this Sandbox .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM