React 단축키

rfc : function
rsf : function div
rcc : class

index.js

만든 파일 모아서 출력해주는 곳

기본적으로 <App /> 만들어져 있어서 출력된 상태로 띄워짐
<App />주석시 흰 화면으로 바뀜

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 /> 1개만 있을때 주석처리하면 흰 화면이 뜸 */}
    <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();

App.js

기본적으로 짜여진 것들 다 지우고 새로 만들어줌
1개의 태그만 return 가능 그래서 div 1개 안에 넣을거 다 넣어야함
<br></br>이 생기기 때문에 <br/>로 닫아줘야함
class가 className으로 쓰인다

import logo from './logo.svg';
import './App.css';

function App() {
  return (
    // 1개의 태그만 return 가능 그래서 div 1개 안에 넣을거 다 넣어야함
    /* <br></br>이 생기기 때문에 <br/>로 닫아줘야함 */
    // class가 className으로 쓰인다
    <div className="App">
      <h3 className='alert alert-info'>리액트 시작!!</h3>
    </div>
  );
}

export default App;

부트스트랩 사용

public 폴더에 있는 index.html
부트스트랩 link 추가하면 됨
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

FirstApp.js

components 폴더에 생성

Mystyle.css

css 파일 따로 만듦

h2.line2{
    width: 500px;
    border: 5px solid pink;
    text-align: center;
}

css 적용

css import

import './Mystyle.css';

적용

{/* App.css에서 style주면 className따라서 적용 가능
다른 css 파일에 style 만들면 위에처럼 import 받아야한다*/}
<h2 className='line2'>FirstApp Component!!!</h2>

태그 style 적용

style 줄때 {{}} 이렇게 주고 해야한다

{/* style 줄때 {{}} 이렇게 주고 해야한다 */}

<div style={{fontSize:'25px',marginLeft:'100px',backgroundColor:'lightgray'}}>
	안녕~~ 오늘은 목요일이야!!
</div>

img 적용

src>image 폴더 생성

이미 넣어두기

이미지 받아오기

import img1 from '../image/4.jpeg';
import img2 from '../image/6.jpeg';
// 이미지는 import 변수 from '경로'로 받아 줘야한다
{/* import 받아온 이미지 넣으려면 {}안에 넣어줘야함 */}
{/* 스타일을 위에 변수에 지정한 것을 적용하려면 {}안에 해줘야함 */}
{/* src의 이미지는 import */}
<img src={img1} style={styleTmg1}/>
<img src={img2} style={{width:'200px', border:'3px dotted pink',marginLeft:'50px'}}/>

public에서 이미지 받아오기

public에 image2 폴더 만들고 이미지 넣기

{/* public image는 직접 호출 가능 */}
<h3>public image</h3>
<img src='../image2/12.jpeg'/>
<img src='../image2/20.jpeg'/>

FirstApp.js 화면 출력

index.js파일 안에 <FirstApp/>추가하면 자동 import 받아짐

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import FirstApp from './components/FirstApp';
import SecondApp from './components/SecondApp';
import ThirdApp from './components/ThirdApp';
import FourthApp from './components/FourthApp';
import FifthApp from './components/FifthApp';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    {/* 아래 <App /> 1개만 있을때 주석처리하면 흰 화면이 뜸 */}
    {/* <App /> */}
    {/* components폴더에 만든 FirstApp.js 화면에 띄워주기 */}
    <FirstApp/>
  </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();

FirstApp.js

import React from 'react';
import './Mystyle.css';
// import '같은 파일경로라면 ./Mystyle.css'
import img1 from '../image/4.jpeg';
import img2 from '../image/6.jpeg';
// 이미지는 import 변수 from '경로'로 받아 줘야한다

// 자동완성 단축키 선생님 카페에 정리 되어 있음
function FirstApp(props) {

    //스타일을 변수에 지정
    const styleTmg1={
        width:'200px',
        border:'5px solid green',
        marginTop:'20px'
    }


    return (
        <div>
            {/* App.css에서 style주면 className따라서 적용 가능
                다른 css 파일에 style 만들면 위에처럼 import 받아야한다*/}
            <h2 className='line2'>FirstApp Component!!!</h2>
            {/* style 줄때 {{}} 이렇게 주고 해야한다 */}
            <div style={{fontSize:'25px',marginLeft:'100px',backgroundColor:'lightgray'}}>
                안녕~~ 오늘은 목요일이야!!
            </div>
            {/* import 받아온 이미지 넣으려면 {}안에 넣어줘야함 */}
            {/* 스타일을 위에 변수에 지정한 것을 적용하려면 {}안에 해줘야함 */}
            {/* src의 이미지는 import */}
            <img src={img1} style={styleTmg1}/>
            <img src={img2} style={{width:'200px', border:'3px dotted pink',marginLeft:'50px'}}/>

            {/* public image는 직접 호출 가능 */}
            <h3>public image</h3>
            <img src='../image2/12.jpeg'/>
            <img src='../image2/20.jpeg'/>
        </div>
    );
}

export default FirstApp;

SecondApp.js

스타일 변수화

	const imgstyle={
        border:'5px solid cadetblue',
        borderRadius:'100px',
        width:'130px'
    }

문자열 변수화

    // 문자도 변수로 줄 수 있음
    let helloEle=<h2 className='alert alert-info'>Hello~~~</h2>

출력문에 포함

    return (
        <div>
            <h2 className='alert alert-danger'>SecondApp입니다</h2>
            <img src={img1} style={imgstyle}/>
            
            {/* 문자열 변수로 준 것 호출 */}
            {helloEle}
            {helloEle}
            {helloEle}
        </div>
    );

SecondApp 화면 출력

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

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    {/* 아래 <App /> 1개만 있을때 주석처리하면 흰 화면이 뜸 */}
    {/* <App /> */}
    {/* components폴더에 만든 FirstApp.js 화면에 띄워주기 */}
    {/* <FirstApp/> */}
    <SecondApp/>
  </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();

이후 js파일 화면 출력들도 이렇게 하나씩 추가하면 된다

SecondApp.js

import React from 'react';
import img1 from '../image/4.jpeg';

function SecondApp(props) {

    const imgstyle={
        border:'5px solid cadetblue',
        borderRadius:'100px',
        width:'130px'
    }

    // 문자도 변수로 줄 수 있음
    let helloEle=<h2 className='alert alert-info'>Hello~~~</h2>

    return (
        <div>
            <h2 className='alert alert-danger'>SecondApp입니다</h2>
            <img src={img1} style={imgstyle}/>
            {/* 문자열 변수로 준 것 호출 */}
            {helloEle}
            {helloEle}
            {helloEle}
        </div>
    );
}

export default SecondApp;

ThirdApp.js

useState(훅스의 많은 기능 중 하나)

-> 값을 변경해주는 훅스

상태관리를 위한 변수 설정
상태변수라 상수 const로 사용
상태 변수는 setMessage로 message 수정해줄 수 있음 [message,setMessage] / [변수,set변수]

useState라는 훅스를 쓰는 순간 위에 import React, { useState } from 'react';로 import됨

const [message,setMessage]=useState('Happy Day')

useState('넣을 값 입력') ()이렇게 빈값으로 주면 비어있는 값

엔터 이벤트 함수

	//엔터 이벤트 함수
    const enterEvent=(e)=>{

        //엔터 치는 순간 값을 비워주는 이벤트
        if(e.keyCode===13){ // e.key==='Enter'로도 줄 수 있음
            setMessage('');
            e.target.value='';
        }
    }

태그에 훅스 및 만든 함수 적용

h3태그에 설정한 변수 {message} 출력 고정

  • defaultValue
    {/* defaultValue={message}로 상수에 준 message를 받아올 수 있음 */}
    <h3 style={{color:'red'}}>{message}</h3>
    input 태그에 defaultValue={message}설정 후

onChange 이벤트 추가

			// onChange가 바로 변환되는 이벤트
            // 이렇게 이벤트 줄 수도 있고, 위에 함수 만들어서 호출하는 방법도 있음
            onChange={(e)=>{
                console.log(e.target.value); // 웹 console을 열어보면 바로바로 나옴
                //message변수에 입력 값 넣기
                setMessage(e.target.value); // e라는 인자값에 target을 주는데 value라는 것을 준다는 이벤트(메소드아님)/ 위에 message를 setMessage로 바로 바꿔줄 수 있는 이벤트
            }}

setMessage 추가 설명
e라는 인자값에 target을 주는데 value라는 것을 준다는 이벤트(메소드아님)
위에 message를 setMessage로 바로 바꿔줄 수 있는 이벤트


onKeyUp 에 만들어 놓은 엔터 이벤트 함수 추가

			// 위에 만들어준 함수 호출
            // onKeyup은 키 입력했을 경우 변환되는 이벤트
            onKeyUp={enterEvent}

출력문 전문

    return (
        <div>
            <h3 className='alert alert-info'>ThirdApp입니다
            <img src={img1} style={{width:'30px'}}/></h3>
            <h3 style={{color:'red'}}>{message}</h3>
            <h4>메세지를 입력해 주세요</h4>
            <input type='text' style={{width:'300px',fontSize:'2em'}}
            defaultValue={message}
            // onChange가 바로 변환되는 이벤트
            // 이렇게 이벤트 줄 수도 있고, 위에 함수 만들어서 호출하는 방법도 있음
            onChange={(e)=>{
                console.log(e.target.value); // 웹 console을 열어보면 바로바로 나옴
                //message변수에 입력 값 넣기
                setMessage(e.target.value); // e라는 인자값에 target을 주는데 value라는 것을 준다는 이벤트(메소드아님)/ 위에 message를 setMessage로 바로 바꿔줄 수 있는 이벤트
            }}
            // 위에 만들어준 함수 호출
            // onKeyup은 키 입력했을 경우 변환되는 이벤트
            onKeyUp={enterEvent}
            />
            {/* defaultValue={message}로 상수에 준 message를 받아올 수 있음 */}
            {/* onChange={(e)=>{ =>는 (e)함수에 넣어줄 이벤트 입력가능
                console.log(e.target.value); e 인자값에 바로 값을 주는 것을 .target.value
                //message변수에 입력 값 넣기
                setMessage(e.target.value); // 위에 setMessage를 바로 바꿔줄 수 있는 이벤트
                }}
            */}
        </div>
    );

ThirdApp.js

import React, { useState } from 'react';
import img1 from '../image/4.jpeg'

function ThirdApp(props) {


    // 상태관리를 위한 변수 설정
    // 상태변수라 상수 const로 사용
    // 상태 변수는 setMessage로 message 수정해줄 수 있음 [message,setMessage] / [변수,set변수]
    const [message,setMessage]=useState('Happy Day') //useState라는 훅스를 쓰는 순간 위에 import React, { useState } from 'react';로 import됨
    // useState('넣을 값 입력') ()이렇게 빈값으로 주면 비어있는 값


    //엔터 이벤트 함수
    const enterEvent=(e)=>{

        //엔터 치는 순간 값을 비워주는 이벤트
        if(e.keyCode===13){ // e.key==='Enter'로도 줄 수 있음
            setMessage('');
            e.target.value='';
        }
    }



    return (
        <div>
            <h3 className='alert alert-info'>ThirdApp입니다
            <img src={img1} style={{width:'30px'}}/></h3>
            <h3 style={{color:'red'}}>{message}</h3>
            <h4>메세지를 입력해 주세요</h4>
            <input type='text' style={{width:'300px',fontSize:'2em'}}
            defaultValue={message}
            // onChange가 바로 변환되는 이벤트
            // 이렇게 이벤트 줄 수도 있고, 위에 함수 만들어서 호출하는 방법도 있음
            onChange={(e)=>{
                console.log(e.target.value); // 웹 console을 열어보면 바로바로 나옴
                //message변수에 입력 값 넣기
                setMessage(e.target.value); // e라는 인자값에 target을 주는데 value라는 것을 준다는 이벤트(메소드아님)/ 위에 message를 setMessage로 바로 바꿔줄 수 있는 이벤트
            }}
            // 위에 만들어준 함수 호출
            // onKeyup은 키 입력했을 경우 변환되는 이벤트
            onKeyUp={enterEvent}
            />
            {/* defaultValue={message}로 상수에 준 message를 받아올 수 있음 */}
            {/* onChange={(e)=>{ =>는 (e)함수에 넣어줄 이벤트 입력가능
                console.log(e.target.value); e 인자값에 바로 값을 주는 것을 .target.value
                //message변수에 입력 값 넣기
                setMessage(e.target.value); // 위에 setMessage를 바로 바꿔줄 수 있는 이벤트
                }}
            */}
        </div>
    );
}

export default ThirdApp;

FourthApp.js

const 변수 훅스 적용

    const [name,setName]=useState('장순영');
    const [age,setAge]=useState(22);

값 출력

            <h3 className='alert alert-info'>FourthApp입니다
            <img src={img2} className='img-thumbnail' style={{width:'40px',marginLeft:'50px'}}/></h3>
            <b style={{fontSize:'25px'}}>이름:{name} <span style={{marginLeft:'20px'}}>나이:{age}</span></b>

값변경 버튼 이벤트 부여

            <button type='button' className='btn btn-info'
            onClick={()=>{
                setName('김영환');
                setAge(25);
            }}>값변경</button>

값 초기화 버튼 이벤트 부여

            <button type='button' className='btn btn-info'
            style={{marginLeft:'20px'}}
            onClick={()=>{
                setName('장순영');
                setAge(22);
            }}>초기화</button>

FourthApp.js

import React, { useState } from 'react';
import img2 from '../image/6.jpeg'

function FourthApp(props) {

    const [name,setName]=useState('장순영');
    const [age,setAge]=useState(22);



    return (

        <div>
            <h3 className='alert alert-info'>FourthApp입니다
            <img src={img2} className='img-thumbnail' style={{width:'40px',marginLeft:'50px'}}/></h3>
            <b style={{fontSize:'25px'}}>이름:{name} <span style={{marginLeft:'20px'}}>나이:{age}</span></b>
            <br/><br/>
            <button type='button' className='btn btn-info'
            onClick={()=>{
                setName('김영환');
                setAge(25);
            }}>값변경</button>

            <button type='button' className='btn btn-info'
            style={{marginLeft:'20px'}}
            onClick={()=>{
                setName('장순영');
                setAge(22);
            }}>초기화</button>
        </div>
    );
}

export default FourthApp;

훅스(useState 사용) 종합 문제

문제

이름 자바점수 리액트점수는 입력시 바로 input 옆에 바로 출력 후 result div에도 출력되도록하고

평균,총점은 결과보기 버튼 누를경우 계산 후 result div에 출력되도록 하기

풀이

name,java,react는 이미 이벤트로 target.value를 부여했기 때문에 버튼 사용시 출력되도록은 힘들다 그러므로 입력과 동시에 input 옆과 result div에 출력되도록 해주면 된다

Number

Number함수 사용법으로
Number(변수)로 해주어야지 값 계산이 가능하다

import React, { useState } from 'react';

function FifthApp(props) {

    const [name,setName]=useState('');
    const [java,setJava]=useState(0);
    const [react,setReact]=useState(0);
    const [total,setTotal]=useState(0);
    const [avg,setAvg]=useState(0);



    return (

        <div>
            <h3 className='alert alert-danger'>FifthApp입니다</h3>
            <div className='inp'>
                이름: <input type='text' style={{width:'100px'}} defaultValue={name}
                onChange={(name)=>{
                    setName(name.target.value);
                }}/>
                <span style={{marginLeft:'10px'}}>{name}</span><br/><br/>
                자바점수: <input type='text' style={{width:'100px'}} defaultValue={java}
                onChange={(java)=>{
                    setJava(java.target.value);
                }}/>
                <span style={{marginLeft:'10px'}}>{java}</span><br/><br/>
                리액트점수: <input type='text' style={{width:'100px'}} defaultValue={react}
                onChange={(react)=>{
                    setReact(react.target.value);
                }}/>
                <span style={{marginLeft:'10px'}}>{react}</span><br/><br/>

                <button type='button' className='btn btn-outline-info'
                onClick={()=>{
                    setTotal(Number(java)+Number(react));
                    setAvg((Number(java)+Number(react))/2);
                }}>결과보기</button>
            </div>
            <div className='result'>
                <span>이름: {name}</span><br/>
                <span>자바점수: {java}</span><br/>
                <span>리액트점수: {react}</span><br/>
                <span>총점: {total}</span><br/>
                <span>평균: {avg}</span>
            </div>
        </div>
    );
}

export default FifthApp;

React 문법 추가 설명

java처럼 변수 선언이 불가능해서 변수 선언을 클래스형태로 불러와야한다
하지만 이것이 불편해서 나중에 훅스 기능이 추가되었고,
이 훅스 기능으로 변수처럼 사용한다

profile
백엔드 개발자로서 성장해 나가는 성현이의 블로그~

0개의 댓글

Powered by GraphCDN, the GraphQL CDN