React用户交互事件

在React中处理用户交互事件(如点击、输入、提交等)的方式与原生JavaScript类似,但有一些语法差异和最佳实践。以下是常见交互事件的处理方法及代码示例:

一、基本事件处理(点击、输入等)

1. 点击事件(onClick)
import React, { useState } from 'react';

const ButtonExample = () => {
  const [count, setCount] = useState(0);

  // 事件处理函数
  const handleClick = () => {
    setCount(count + 1);
  };

  return (
    
  );
};
2. 输入事件(onChange)
const InputExample = () => {
  const [text, setText] = useState('');

  const handleChange = (event) => {
    setText(event.target.value);  // 获取输入值
  };

  return (
    
  );
};
3. 表单提交(onSubmit)
const FormExample = () => {
  const [name, setName] = useState('');

  const handleSubmit = (event) => {
    event.preventDefault();  // 阻止默认提交行为
    console.log('Submitted:', name);
  };

  return (
    
setName(e.target.value)} />
); };

二、传递参数给事件处理函数

方法1:使用箭头函数
const ListItem = ({ id, text }) => {
  const handleDelete = () => {
    console.log('Deleting item:', id);
    // 调用父组件的删除函数
  };

  return (
    
  • {text}
  • ); };
    方法2:使用bind
    
    

    三、事件委托(处理多个子元素)

    当需要处理多个相似元素的事件时,推荐使用事件委托:

    const ColorSelector = () => {
      const [selectedColor, setSelectedColor] = useState('');
    
      const handleColorClick = (color) => {
        setSelectedColor(color);
      };
    
      const colors = ['red', 'green', 'blue'];
    
      return (
        

    Selected: {selectedColor}

    {colors.map(color => ( ))}
    ); };

    四、高级事件处理

    1. 键盘事件(onKeyDown)
    const KeyPressExample = () => {
      const handleKeyDown = (event) => {
        if (event.key === 'Enter') {
          console.log('Enter key pressed!');
        }
      };
    
      return (
        
      );
    };
    
    2. 自定义事件组件

    创建可复用的事件处理组件:

    // CustomButton.js
    const CustomButton = ({ onClick, children }) => {
      return (
        
      );
    };
    
    // 使用自定义按钮
    const App = () => {
      const handleClick = () => {
        console.log('Custom button clicked!');
      };
    
      return (
        
          Click me
        
      );
    };
    

    五、注意事项

    1. 事件名称使用驼峰命名

      • HTML:onclick → React:onClick
      • HTML:onchange → React:onChange
    2. 避免直接修改DOM
      不要使用 document.getElementById(),而是通过状态管理更新UI。

    3. 受控组件 vs 非受控组件

      • 受控组件:值由React管理(如上面的输入框示例)
      • 非受控组件:使用 ref 获取DOM值(适用于文件上传等场景)
    // 非受控组件示例
    const FileInput = () => {
      const fileInput = useRef(null);
    
      const handleSubmit = (event) => {
        event.preventDefault();
        console.log('File:', fileInput.current.files[0]);
      };
    
      return (
        
    ); };

    你可能感兴趣的:(React用户交互事件)