import { Component } from "react";
class Counter extends Component{
constructor(props) {
super(props);
this.state = { number : 0 };
}
render(){
const {number} = this.state;
return (
<div>
<h1>{number}</h1>
<button onClick={() => {
this.setState({number : number + 1});
}}>
+1
</button>
</div>
);
}
}
export default Counter;
//App.js
//import Counter from './Counter';
//
// const App = () => {
// return <Counter/>
// };
//
// export default App;
### Counter Component
1. **Importing Component from React**: The first line imports `Component` from the React library, enabling the definition of a class component by extending `Component`.
2. **Class Component Definition**: The `Counter` class extends `Component`, indicating that it is a React component with its own state and lifecycle methods.
3. **Constructor and State Initialization**:
- The constructor method initializes the component's state with a property named `number`, set to `0`. This is the starting value of the counter.
- The `super(props)` call is necessary to ensure the component inherits correctly from its parent class, `Component`.
4. **State Deconstruction in render Method**: Inside the `render` method, the current state's `number` value is deconstructed from `this.state`, making it easier to reference within the JSX.
5. **JSX Output**:
- The component returns a `div` element containing an `h1` element to display the current value of `number`.
- A button is included, with an `onClick` event handler that updates the state's `number` by incrementing it by 1 every time the button is clicked. This is achieved through the `this.setState()` method, which triggers a re-render of the component with the updated state.
### Integration with App Component
- The `Counter` component is intended to be used within an `App` functional component, as illustrated in the commented-out `App.js` code snippet. The `App` component simply renders the `Counter` component, showcasing how components can be modular and reused across different parts of a React application.
'개념 > React' 카테고리의 다른 글
SCSS) ..... utils.scss (0) | 2025.04.14 |
---|---|
React) basic_Component (1) | 2025.04.13 |
React) class_component_props (0) | 2025.04.11 |
React) isRequired (0) | 2025.04.10 |
React) multiple state value (0) | 2025.04.09 |