본문 바로가기
개념/React

Reat) click the button print out comment value set empty

by kiseno 2025. 4. 1.
728x90
반응형
SMALL
import { Component } from 'react';

class EventPractice extends Component{
    state = {
        message : ''
    }
    render() {
        return (
            <div>
                <h1>Event practice</h1>
                <input
                    type="text"
                    name="message"
                    placeholder="아무거나 입력하시오."
                    onChange={
                        (e) => {
                            this.setState({
                                message: e.target.value
                            })
                        }
                    }
                />
                <button onClick ={
                    () => {
                        alert(this.state.message);
                        this.setState({
                            message : ''
                        });
                    }
                }>확인</button>
            </div>
        );
    }
}

export default EventPractice;

### Component Overview

1. **State Initialization**:
   ```jsx
   state = {
       message: ''
   }
   ```
   This line initializes the component's state with a `message` property, initially set to an empty string. This state will store the value entered in the text input field.

2. **Rendering the Component**:
   ```jsx
   render() {
       return (
           <div>
               <h1>Event practice</h1>
               <input
                   type="text"
                   name="message"
                   placeholder="아무거나 입력하시오."
                   onChange={this.handleChange}
               />
               <button onClick={this.handleClick}>확인</button>
           </div>
       );
   }
   ```
   - The `render` method returns JSX to be rendered to the DOM. It includes an `<h1>` tag for the title, a text input, and a button.
   - The `input` element is configured to handle changes via an `onChange` event. Each time the input changes, `handleChange` is called (which will be explained shortly).
   - The `button` element has an `onClick` event that triggers `handleClick` when clicked (also explained shortly).

3. **Handling Input Changes**:
   ```jsx
   onChange={(e) => {
       this.setState({
           message: e.target.value
       });
   }}
   ```
   - This inline function is executed whenever the input field changes (i.e., as the user types).
   - It uses `setState` to update the `message` state with the current value of the input field (`e.target.value`), effectively making the input field a controlled component.

4. **Handling Button Clicks**:
   ```jsx
   onClick={() => {
       alert(this.state.message);
       this.setState({
           message: ''
       });
   }}
   ```
   - This inline function is triggered when the button is clicked.
   - It first uses `alert` to display the current `message` state, showing the user what they typed.
   - Then, it clears the `message` state by setting it back to an empty string, clearing the input field.

### Exporting the Component
```jsx
export default EventPractice;
```
- This line allows the `EventPractice` component to be imported and used elsewhere in a React application.

### Suggestions for Improvement

- **Refactoring Event Handlers**: To keep the `render` method cleaner and improve the component's maintainability, you can define `handleChange` and `handleClick` methods within the class instead of using inline functions. Here's how you might refactor it:
  ```jsx
  handleChange = (e) => {
      this.setState({ message: e.target.value });
  }

  handleClick = () => {
      alert(this.state.message);
      this.setState({ message: '' });
  }
  ```
  Then update the JSX to use these methods:
  ```jsx
  <input
      type="text"
      name="message"
      placeholder="아무거나 입력하시오."
      onChange={this.handleChange}
  />
  <button onClick={this.handleClick}>확인</button>
  ```

This component is an excellent example of handling basic form elements and events in React, making it a good starting point for beginners learning about state management and UI events in React components.

728x90
반응형
LIST

'개념 > React' 카테고리의 다른 글

React) pull out constructor from state  (0) 2025.04.03
React) this setState function parameter  (0) 2025.04.02
React) Event basic  (0) 2025.03.31
React) Event Practice 1  (0) 2025.03.30
React) Event Practice 2  (0) 2025.03.29