在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 (
<input
type="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}>
<input
type="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 => (
<button
key={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 (
<input
type="text"
onKeyDown={handleKeyDown}
/>
);
};
2. 自定义事件组件
创建可复用的事件处理组件:
// CustomButton.js
const CustomButton = ({ onClick, children }) => {
return (
<button
className="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>
);
};