Skip to content

React Event Handling คือ

Basic Event Handling

การจัดการเหตุการณ์พื้นฐานใน React โดยการใช้ onClick เพื่อจัดการเหตุการณ์การคลิก

Handling Form Events

การจัดการเหตุการณ์ในฟอร์ม เช่น การเปลี่ยนแปลงของช่องกรอกข้อมูลและการส่งฟอร์ม

jsx
import React, { useState } from 'react';

export default function FormComponent() {
  const [inputValue, setInputValue] = useState('');

  const handleChange = (event) => {
    setInputValue(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault(); // Prevents the default form submission
    alert('Form submitted with value: ' + inputValue);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" value={inputValue} onChange={handleChange} />
      <button type="submit">Submit</button>
    </form>
  );
}

Event Handling with Parameters

การส่งพารามิเตอร์ให้กับฟังก์ชันเหตุการณ์

jsx
import React from 'react';

export default function GreetingComponent() {
  const greet = (name) => {
    alert(`Hello, ${name}!`);
  };

  return (
    <button onClick={() => greet('John')}>Greet John</button>
  );
}

Handling Multiple Events

การจัดการหลายเหตุการณ์ในคอมโพเนนต์เดียว

jsx
import React from 'react';

export default function MultiEventComponent() {
  const handleClick = () => {
    alert('Button clicked!');
  };

  const handleMouseOver = () => {
    alert('Mouse over the button!');
  };

  return (
    <button onClick={handleClick} onMouseOver={handleMouseOver}>
      Hover and Click me
    </button>
  );
}

Custom Event Handlers

การสร้างฟังก์ชันจัดการเหตุการณ์ที่กำหนดเองและใช้งานในคอมโพเนนต์

jsx
import React from 'react';

export default function CustomHandlerComponent() {
  const customHandler = (event) => {
    console.log('Event type:', event.type);
    console.log('Event target:', event.target);
  };

  return (
    <button onClick={customHandler}>Click me</button>
  );
}

Preventing Default Behavior

การป้องกันพฤติกรรมเริ่มต้นของเหตุการณ์ เช่น การส่งฟอร์ม

jsx
import React from 'react';

export default function PreventDefaultComponent() {
  const handleClick = (event) => {
    event.preventDefault(); // Prevents the default action
    alert('Link was clicked, but default action was prevented.');
  };

  return (
    <a href="https://example.com" onClick={handleClick}>
      Click this link
    </a>
  );
}

Using Event Handlers with this

การใช้งาน this กับฟังก์ชันจัดการเหตุการณ์ในคอมโพเนนต์ที่ใช้คลาส

jsx
import React, { Component } from 'react';

export default class ClassComponent extends Component {
  handleClick = () => {
    alert('Button clicked!');
  };

  render() {
    return (
      <button onClick={this.handleClick}>Click me</button>
    );
  }
}

Released under the MIT License