在 React 中处理 onPaste 事件(附示例)
Handle the onPaste event in React (with examples)
在 React 中处理 onPaste 事件:
- 在元素上设置道具或在
对象onPaste
上添加事件侦听器。window
- 提供事件处理函数。
- 访问粘贴的值作为
event.clipboardData.getData('text')
。
应用程序.js
import {useEffect} from 'react'; export default function App() { const handlePaste = event => { console.log(event.clipboardData.getData('text')); }; useEffect(() => { const handlePasteAnywhere = event => { console.log(event.clipboardData.getData('text')); }; window.addEventListener('paste', handlePasteAnywhere); return () => { window.removeEventListener('paste', handlePasteAnywhere); }; }, []); return ( <div> <h2>Hello world</h2> {/* 👇️ handle paste event on an input field */} <input onPaste={handlePaste} type="text" id="message" autoComplete="no" /> </div> ); }
代码示例显示了如何处理
字段或对象上的粘贴
事件。input
window
该paste
事件在用户启动paste
操作时触发。
We can use the
getData()
method on the clipboardData
property of the event
object to access the data
the user pasted.
App.js
const handlePaste = event => { console.log(event.clipboardData.getData('text')); };
The second example shows how to listen for the paste
event on the window
object.
App.js
useEffect(() => { const handlePasteAnywhere = event => { console.log(event.clipboardData.getData('text')); }; window.addEventListener('paste', handlePasteAnywhere); return () => { window.removeEventListener('paste', handlePasteAnywhere); }; }, []);
We passed an empty dependencies array to the
useEffect hook
because we only want to register the paste
event listener once – when the
component mounts.
The function we returned from the
useEffect
hook is called when the component unmounts.We used the
removeEventListener
method to remove the event listener that we previously registered.
The cleanup step is important, because we want to make sure we don’t have any
memory leaks in our application.