MST

星途 面试题库

面试题:React中如何处理键盘按下事件并识别特定按键

在React项目中,要求编写一个组件,当用户按下键盘上的某个特定按键(比如回车键)时,在控制台打印出一条消息,描述你将如何实现这个功能,需给出关键代码片段。
33.5万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试
  1. 使用useEffectuseRef钩子来实现

    • 首先,我们需要在组件中添加一个ref来引用DOM元素,这样我们可以在该元素上添加键盘事件监听器。
    • 然后使用useEffect来在组件挂载时添加事件监听器,并在组件卸载时移除监听器,以避免内存泄漏。
    import React, { useEffect, useRef } from'react';
    
    const MyComponent = () => {
      const inputRef = useRef(null);
    
      useEffect(() => {
        const handleKeyDown = (event) => {
          if (event.key === 'Enter') {
            console.log('回车键被按下');
          }
        };
        if (inputRef.current) {
          inputRef.current.addEventListener('keydown', handleKeyDown);
        }
        return () => {
          if (inputRef.current) {
            inputRef.current.removeEventListener('keydown', handleKeyDown);
          }
        };
      }, []);
    
      return <input ref={inputRef} type="text" />;
    };
    
    export default MyComponent;
    
  2. 使用onKeyDown属性直接在输入元素上绑定事件处理函数

    • 这种方式更简洁,直接在input元素上绑定onKeyDown事件处理函数。
    import React from'react';
    
    const MyComponent = () => {
      const handleKeyDown = (event) => {
        if (event.key === 'Enter') {
          console.log('回车键被按下');
        }
      };
    
      return <input onKeyDown={handleKeyDown} type="text" />;
    };
    
    export default MyComponent;