面试题答案
一键面试-
使用
useEffect
和useRef
钩子来实现:- 首先,我们需要在组件中添加一个
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;
- 首先,我们需要在组件中添加一个
-
使用
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;
- 这种方式更简洁,直接在