본문 바로가기

카테고리 없음

React State (useState)

Counter.js

import React, {Component} from 'react';

class Counter extends Component{

    // constructor : 생성자
    // super: 부모의 생성자, 나의 부모다 있으면 부모의 객체를 먼저 생성
    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 './App.css';

import Counter from './Counter';


//JSX

function App(){
  
  return(
    <>
      <Counter></Counter>
    </>
  )

}


export default App;

 

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

 

https://piaocanyi.tistory.com/317