본문 바로가기

kosta_이론

25.04.16 react state

x = v1 || v2

v1이 truthy한 값이면 v2는 계산하지 않고 v1 반환

v1이 falsy한 값이면 v2 반환

 

x = v1 ?? v2

v1이 null도 아니고 undefined도 아니면 v1 할당 / 그 외의 경우 v2할당

 

spread

기존 배열이나 객체의 전체 또는 일부를 다른 배열이나 객체로 복사

... > spread 연산자

let a = [1,2];
let b = [3,4];
let c = a.concat(b);
console.log(c);
let d = [...a,...b];
console.log(d);

let b1 = a; //주솟값 복사
console.log(b1 === a); //true
console.log(b1 === b); //false

let b2 = [...a]; //값 복사
console.log(b2 === a); //false
console.log(b2 === b); //false

 

let student = {
    name : '홍길동',
    score : 90
}
let student1 = student; //주소값 복사
console.log(student1 === student); //true
student1.name = '김연아';
console.log(`${student1.name}, ${student.name}`); //side effect
let student2 = {...student};
console.log(student2 === student); //false

 

let student1 = student; //주소값 복사
let student2 = {...student};
let student3 = {...student, add : '주소'};
let student4= {...student, name: '박지성'};
console.log(student1 === student); //true
student1.name = '김연아';
console.log(`${student1.name}, ${student.name}`); //side effect


console.log(`${student3.name},${student3.add},${student4.name}`);
 
//결과
true
김연아, 김연아
홍길동,주소,박지성

 

 

배열메서드

• 요소 추가 및 삭제(push, pop, shift, unshift, slice, concat)
• push, pop : 맨 뒤에 추가하고 맨 뒤의 element 를 삭제
• unshift, shift, : 맨 앞에 추가하고 맨 앞의 element 를 삭제
• 순회(foreach)
• 탐색 (indexOf, includes, findIndex, find, filter)
• 변형(map, sort, join, reduce)

let arr = [1,2,3];
arr.push(4); //4추가
console.log(arr);
let ret = arr.pop(); //맨 뒤 요소 삭제
console.log(ret); //4
console.log(arr); //[1,2,3]

arr.unshift(0); //맨 앞에 0 추가
console.log(arr); //[0,1,2,3]
ret = arr.shift(); //맨 앞 제거
console.log(ret); //0
console.log(arr); //[1,2,3]
let str = "abc";
let sr = ["aaa","abc","bbb","dvd"].includes(str); //true
console.log(sr);

 

react element / dom element

• React elements는 화면에서 보이는 것들을 기술
  - 자바스크립트 (불변성을 가진) 객체 형태로 존재
  - Element 생성 후에는 children 이나 attribute 를 변경할 수 없는 immutable 객체임
• React elements의 기술 내용을 토대로 웹 브라우저에 보이는 DOM element가 생성됨

 

html과 react 비교

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="root"></div>
</body>
<script>
    const root = document.getElementById("root");
    const p = React.createElement("p", {id:"count",
              style: {color:"blue"}}, "This is a p tag");
    const btn = React.createElement("button",
                {onClick: () => console.log("button click")},"Click");
    const app = React.createElement("div",null,[p,btn]);
    ReactDOM.render(app,root);
</script>
</html>
function App() {
  const [count, setCount] = useState(0)

  return (
      <div>
        <p>{count}번 클릭됨</p>
        <button onClick={() => setCount((count) => count + 1)}>
          Click
        </button>
      </div>
  )
}
export default App

export default App

import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.jsx'

createRoot(document.getElementById('root')).render(
    <App />
)

JSX는 HTML과 유사한 문법(createElement 대체)으로 element를 생성해주는 JavaScript를확장한 문법

createElement 함수의 파라미터
• type : div, span, react의 component 등
• props : 속성
• children : child element

 

장점 : 간결한 코드, 높은 가독성, 보안성이 좋음(Injection 공격 방어)

기본 문법 : html과 javascript가 섞인 형태로 작성, html 안에 {javascript 코드} 적어주면 됨

 

규칙
• 태그는 닫혀 있어야 함
• 두 개 이상의 태그는 하나의 태그안에 감싸져야 함
• 내부에 Javascript 값 사용할 수 있음 – {변수}
• 내부에 CSS 사용함 – camelCase로 작성
• 외부의 css파일은 import ‘./App.css’ 로 가져오고 className=“클래스”를 사용
• 주석 : {/* 주석 */} , 태그 내부에 주석 작성할 때는 // 사용 가능

import Hello from "./Hello";

//1개 이상의 태그를 리턴 시 빈태그로 묶어줘야함
function App() {
  let name = '홍길동';
  const style = {
    backgroundColor: "yellow"
  }
  return (
    <>
      <h1 style={style}>hello ,{name}</h1>
      <p>안녕하세요</p>
      <Hello/>
      <Hello/>
      <Hello/>
    </>
  )
}


export default App
function Hello() {
    const style = {
        backgroundColor: "blue",
        color: "white"
      }
    return (
        <P style={style}>hello</P>
    )
}
export default Hello

 

 

Props : properties의 줄임말, html tag의 속성와 유사, 컴포넌트 사용시 특정 값 전달

JSX : JavaScript를 확장한 문법(JavaScript + XML), 자바스크립트의 공식 문법이 아님
브라우저에서 인식되지 않는다고 오류가 발생 > 실행 전 Babel transformer를 이용하여 JavaScrtip코드로 변환해줘야 함

• Babel은 최신 버전의 JavaScript 코드를 이전 버전으로 변환해주는 도구
JavaScrtipt 와 Html와 유사하게 작성하는 것이 JSX의 가장 큰 장점임

 

컴포넌트
• 재사용 가능한 UI를 나타내며, 함수나 클래스를 사용하여 정의할 수 있음

함수형

function Hello() {  const name = "world"; return <p> {name} </p>; }

클래스

class Welcome extends React.Component { render() { return <h1>hello, {this,props.name}</h1>; }  }

 

 

 

state : 데이터가 저장되는 곳, 컴포넌트 내부에서 변경 가능한 데이터를 관리
• this.state 객체를 통해 사용
• setState() 메서드를 사용하여 변경
• state의 변경은 render() 메서드를 트리거하고 UI를 업데이트함
props : 부모 컴포넌트에서 자식 컴포넌트로 전달되는 읽기 전용 데이터

 

import { useState } from 'react'
import './App.css'

function App() {
  let [count, setCount] = useState(0);

  return (
      <div>
        <p>{count}번 클릭됨</p>
        <button onClick={()=> {
          setCount((count) => count + 1);
        }}>
          Click
        </button>
      </div>
  )
}
export default App
 

import { useState } from 'react'
import './App.css'

function App() {
  let [count, setCount] = useState(0);
  let [bool, setBool] = useState(true);
  let [hello, setHello] = useState('a');

  return (
      <div>
        <p>{count}번 클릭됨</p>
        <p>{bool ? "ture" : "false"}</p>
        <p>{hello}</p>
        <button onClick={()=> {
          setCount((count) => count + 1);
        }}>
          Click - count
        </button>
        <br/>
        <button onClick={() => {
          setBool((bool) => !bool);
        }}>
          Click - true/false
        </button>
        <button onClick ={() => {
          setHello((hello) => hello + 'a');
        }}>
          Click - hello a
        </button>
        <p>{console.log(`${count} + ${bool} + ${hello}`)}</p>
      </div>
  )
}
export default App

 

import { useState } from "react"

function Form2() {
    const [person, setPerson] = useState({
        name:"", age:0, email:""
    }); //빈객체로 줌
    const inputUpdate = (e) => {
        const {name, value} = e.target;
        setPerson({
            ...person,
            [name] : value
        });
    }
    return (
        <>
        <h2>form2</h2>
        <input type="text" name="name" value={person.name} onChange={inputUpdate}/>
        <input type="text" name="age" value={person.age} onChange={inputUpdate}/>
        <input type="text" name="email" value={person.email} onChange={inputUpdate}/>
        <p>{console.log(person)}</p>
        </>
    )
}

export default Form2

 

 

 

import { useState } f
rom "react"
import LengthConverter from "./LengthConvert"
import TimeConverter from "./TimeConvert"

function App() {
    const [index, setIndex] = useState("0");
    const onSelect = (e) => {
        setIndex(e.target.value);
    }
    console.log(index);
    return (
        <>
        <select name="converter" id="converter" onChange={onSelect}>
            <option value="0" selected>Select unit Converter</option>
            <option value="1">Time Converter</option>
            <option value="2">Length Converter</option>
        </select>
            {index == 1 ? <TimeConverter/> : null}
            {index == 2 ?<LengthConverter /> : null}
        </>
    )
}
export default App

import { useState } from "react"

function LengthConverter() {
    const [numbers, setNumbers] = useState(0);
    const [inverted, setInverted] = useState(false);
    const timeConvert = (e) => {
        setNumbers(e.target.value);
    }
    const invertChange = () => {
        setInverted(!inverted);
    }
    const onReset = () => {
        setNumbers(0);
    }
    return (
        <>
        <h1>Length Converter</h1>
        <label htmlFor="minutes">m</label>

        <input type="text" id="minutes" placeholder="미터"
        value={inverted ? numbers *1000 : numbers}
        disabled={inverted}
        onChange={timeConvert}/>

        <label htmlFor="hours">km</label>
        <input type="text" id="hours" placeholder="키로미터"
        value={inverted ? numbers : Math.round(numbers/1000)}
        disabled={!inverted}
        onChange={timeConvert}/>

        <button onClick={onReset}>Reset</button>
        <button onClick={invertChange}>{inverted ? "Forward" : "Backward"}</button>
        </>
    )
}
export default LengthConverter

import { useState } from "react"

function TimeConverter() {
    const [numbers, setNumbers] = useState(0);
    const [inverted, setInverted] = useState(false);
    const timeConvert = (e) => {
        setNumbers(e.target.value);
    }
    const invertChange = () => {
        setInverted(!inverted);
    }
    const onReset = () => {
        setNumbers(0);
    }
    return (
        <>
        <h1>Time Converter</h1>
        <label htmlFor="minutes"></label>

        <input type="text" id="minutes" placeholder="분"
        value={inverted ? numbers *60 : numbers}
        disabled={inverted}
        onChange={timeConvert}/>

        <label htmlFor="hours">시간</label>
        <input type="text" id="hours" placeholder="시간"
        value={inverted ? numbers : Math.round(numbers/60)}
        disabled={!inverted}
        onChange={timeConvert}/>

        <button onClick={onReset}>Reset</button>
        <button onClick={invertChange}>{inverted ? "Forward" : "Backward"}</button>
        </>
    )
}
export default TimeConverter

'kosta_이론' 카테고리의 다른 글

2025.04.19 게시판 crud 만들기  (1) 2025.04.19
25.04.17 react props  (1) 2025.04.19
25.04.15 react  (1) 2025.04.15
25.04.11 jquery + 애니메이션study  (1) 2025.04.11
25.04.10 js 객체 및 이벤트  (0) 2025.04.10