在React中處理用戶交互事件(如點擊、輸入、提交等)的方式與原生JavaScript類似,但有一些語法差異和最佳實踐。以下是常見交互事件的處理方法及代碼示例:
一、基本事件處理(點擊、輸入等)
1. 點擊事件(onClick)
import React, { useState } from 'react';const ButtonExample = () => {const [count, setCount] = useState(0);// 事件處理函數const handleClick = () => {setCount(count + 1);};return (<button onClick={handleClick}> {/* 綁定事件 */}Click me: {count}</button>);
};
2. 輸入事件(onChange)
const InputExample = () => {const [text, setText] = useState('');const handleChange = (event) => {setText(event.target.value); // 獲取輸入值};return (<inputtype="text"value={text} // 受控組件onChange={handleChange}/>);
};
3. 表單提交(onSubmit)
const FormExample = () => {const [name, setName] = useState('');const handleSubmit = (event) => {event.preventDefault(); // 阻止默認提交行為console.log('Submitted:', name);};return (<form onSubmit={handleSubmit}><inputtype="text"value={name}onChange={(e) => setName(e.target.value)}/><button type="submit">Submit</button></form>);
};
二、傳遞參數給事件處理函數
方法1:使用箭頭函數
const ListItem = ({ id, text }) => {const handleDelete = () => {console.log('Deleting item:', id);// 調用父組件的刪除函數};return (<li>{text}<button onClick={() => handleDelete(id)}> {/* 傳遞參數 */}Delete</button></li>);
};
方法2:使用bind
<button onClick={handleDelete.bind(this, id)}>Delete
</button>
三、事件委托(處理多個子元素)
當需要處理多個相似元素的事件時,推薦使用事件委托:
const ColorSelector = () => {const [selectedColor, setSelectedColor] = useState('');const handleColorClick = (color) => {setSelectedColor(color);};const colors = ['red', 'green', 'blue'];return (<div><p>Selected: {selectedColor}</p>{colors.map(color => (<buttonkey={color}style={{ background: color }}onClick={() => handleColorClick(color)} {/* 統一處理 */}>{color}</button>))}</div>);
};
四、高級事件處理
1. 鍵盤事件(onKeyDown)
const KeyPressExample = () => {const handleKeyDown = (event) => {if (event.key === 'Enter') {console.log('Enter key pressed!');}};return (<inputtype="text"onKeyDown={handleKeyDown}/>);
};
2. 自定義事件組件
創建可復用的事件處理組件:
// CustomButton.js
const CustomButton = ({ onClick, children }) => {return (<buttonclassName="custom-button"onClick={onClick} {/* 暴露事件接口 */}>{children}</button>);
};// 使用自定義按鈕
const App = () => {const handleClick = () => {console.log('Custom button clicked!');};return (<CustomButton onClick={handleClick}>Click me</CustomButton>);
};
五、注意事項
-
事件名稱使用駝峰命名:
- HTML:
onclick
→ React:onClick
- HTML:
onchange
→ React:onChange
- HTML:
-
避免直接修改DOM:
不要使用document.getElementById()
,而是通過狀態管理更新UI。 -
受控組件 vs 非受控組件:
- 受控組件:值由React管理(如上面的輸入框示例)
- 非受控組件:使用
ref
獲取DOM值(適用于文件上傳等場景)
// 非受控組件示例
const FileInput = () => {const fileInput = useRef(null);const handleSubmit = (event) => {event.preventDefault();console.log('File:', fileInput.current.files[0]);};return (<form onSubmit={handleSubmit}><input type="file" ref={fileInput} /><button type="submit">Submit</button></form>);
};