import { Component } from "react";
class Counter extends Component{
constructor(props) {
super(props);
this.state = {
number: 0,
fixedNumber: 0
};
}
render(){
const {number, fixedNumber} = this.state;
return (
<div>
<h1>{number}</h1>
<h2> Not change value : {fixedNumber}</h2>
<button onClick={() => {
this.setState(({number : number + 1}));
}}>
+1
</button>
</div>
);
}
}
export default Counter;
### Component Structure and State
1. **Initialization**: The `Counter` class extends `Component`, making it a React component. Within its constructor, it initializes its state with two properties: `number` and `fixedNumber`. Initially, both `number` and `fixedNumber` are set to `0`. The state is where you store property values that belong to the component. When the state changes, the component responds by re-rendering.
2. **State Destructuring in Render Method**: Within the `render` method, both `number` and `fixedNumber` are extracted from `this.state`. This technique simplifies access to these state properties within the JSX.
### JSX and Interaction
3. **Displaying State**: The component renders a `div` that contains two headings (`<h1>` and `<h2>`) and a button. The `<h1>` element displays the current value of `number`, and the `<h2>` element displays `fixedNumber`. Since `fixedNumber` is not updated on button clicks, its value remains constant, demonstrating how some parts of the state can remain unchanged despite interactions.
4. **Updating State**: The button is equipped with an `onClick` event handler, which updates the component's state when clicked. Specifically, it increments the `number` property by 1 each time it is clicked. This is achieved through the `this.setState` method, a key part of React's state management system that schedules updates to the component's state object and tells React that this component and its children need to be re-rendered with the updated state.
### Syntax Error in `setState` Call
There is a minor syntax error in the `setState` call within the `onClick` handler. The correct way to update the state based on the previous state in a class component is by passing a function to `setState` that returns the updated state object. Here's the corrected line:
```
this.setState(prevState => ({
number: prevState.number + 1
}));
```
'개념 > React' 카테고리의 다른 글
React) class_component_props (0) | 2025.04.11 |
---|---|
React) isRequired (0) | 2025.04.10 |
React) mycomponent (0) | 2025.04.08 |
React) mycomponent props children (0) | 2025.04.07 |
React) myComponent props value (0) | 2025.04.06 |