React Native 监听/唤起/收起键盘

949 阅读1分钟

需要有输入框才能唤起键盘:

const textInputRef = useRef(null);

return <TextInput ref={textInputRef}>

监听键盘弹出/收起:

useEffect(() => {
  //监听键盘弹出
  const keyboardDidShowListener =Keyboard.addListener(
    'keyboardDidShow',
    // 键盘弹出的回调函数
    () => {}
  );

  //监听键盘收起
  const keyboardDidHideListener =Keyboard.addListener(
    'keyboardDidHide',
    // 键盘收起的回调函数,这里dismiss是为了避免特殊情况下键盘收起后无法通过点击原输入框来唤起键盘
    () => {Keyboard.dismiss()}
  );

  // 返回一个清理函数以在组件卸载时取消监听
  return () => {
    keyboardDidShowListener.remove();
    keyboardDidHideListener.remove();
  };
}, []);

控制键盘弹出/收起:

const handleKeyboardButtonPress = () => {
  if (textInputRef.current?.isFocused()) {
    Keyboard.dismiss(); //收起键盘
  } else {
    textInputRef.current.focus(); //唤起键盘
  }
};

如果有多个输入框,需要注意区别聚焦于哪个输入框!