App.js 에서 사용되는 html 문법은 사실 JSX 임
-JSX = .js 파일에서 쓰는 html 대대품
react 에서 html 내용은 return ( 여기 안에만 작성 가능 )
JSX 문법 정리
1. CSS Class 명 설정
class 대신 className
2. 변수 넣을 때는 {중괄호}
{/* document.querySelector('h4').innerHTML = post; js 기본 문법 */}
<h4> id = {post}</h4>
데이터 바인딩 = 원하는 곳에 데이터 꽂을 수 있음
3.style 넣을 때
object 형으로 중괄호 안에 넣어줘야 함
//이렇게 쓰면 안댐 style = "color : red "
<h4 style={{color : 'red', fontSize : '16px'}}>
주의 : font-size 안됨 = js 이기때문에 - 기호가 안되서 fontSize 같이 다 camel 스타일로 바꿔줘야 함
4. return() 안에 병렬 두개 태그 금지
<div> </div>
<div> </div>
// 이거 안댐
5. state 란 ?
= 변수 (let, var, const) : 자료 잠깐 보관
react 에서는 state 문법을 이용 가능
// import
import {useState} from 'react';
// 작명
let [a, b] = useState('커피 맛집 추천');
// a = 자료 = '커피 맛집 추천'
// b = state 변경 도와주는 함수
// 여러개 쓰고 싶다
let [title, a] = useState(['일식 맛집 추천', '양식 맛집 추천', '중식 맛집 추천']);
// 배열로 뽑으면 댐 => title[0]
변수와 state 의 차이점
- 변수는 값이 변했을 때 변경이 자동으로 되지 않음
- state 는 자동으로 html 이 자동 렌더링
warning 메시지 거슬린다.
상단에 한줄 추가
/* eslint-disable */
6. state 변경하기
- 좋아요 개수, 버튼 클릭 이벤트로 구현
- react 에서의 클릭 이벤트 핸들러 onClick= { 온클릭 안에는 함수를 넣어야 함 }
let [like, likeFunction] = useState(0);
<h4>{title[0]} <span onClick={() => {
likeFunction(like + 1)
}}>👍</span> {like} </h4>
- state 는 = 로 변경 안댐, state 만들 때 선언했던 함수로 변경해야 함
7. state 변경하기 2 (state 변경함수 특징)
- 여러 값 변경할 때, 즉 array/object 다룰 때 원본은 보존하는 게 좋음
ex ) 아래와 같은 state 에서 일식만 한식으로 바꿀 떄
let [title, titleFunction] = useState(['일식 맛집 추천', '양식 맛집 추천', '중식 맛집 추천']);
-개떡 방법 1 ( 안되는 이유 밑에서 설명함. 자바는 될거 같은데... )
<button onClick={() => {
titleFunction( title[0] = '한식 맛집 추천');
}}>변경버튼</button>
- 개떡 방법 2 (동작은 잘 되는데, 데이터 많으면 어떡할래? )
<button onClick={() => {
titleFunction(['한식 맛집 추천', '양식 맛집 추천', '중식 맛집 추천']);
}}>변경버튼</button>
-- 개떡 방법 3 (될 줄 알았지? )
<button onClick={() => {
let copy = title;
copy[0] = '한식 맛집 추천';
titleFunction(copy);
}}>변경버튼</button>
ㄴ 이게 안되는 이유
1. state 변경함수 특징 : data 를 갈아치우기 전에 비교해서 원래랑 똑같으면 변경 안해줌
2. array/object in js 특징 : reference data type
= js 에서 array[] 는 데이터를 넣는게 아니라 담은 변수에 좌표만 찍어줌
- 이거 떄문에 1번 에서 동작 안함 = > array 는 수정됐어 근데 좌표는 수정 안댐
빡대가리식 설명
let arr = [1,2,3] 이면 [1,2,3] 은 ram 에 들어가 있고 arr 는 그게 어디있는지 화살표로 가르키는 거
그냥 state 가 array/object 면 그냥 shallow copy 즉 복사본 만들어서 변경해야 함
- 옳은 방법
<button onClick={() => {
let copy = [...title];
copy[0] = '한식 맛집 추천';
titleFunction(copy);
}}>변경버튼</button>
... = 괄호 벗겨주세요, 화살표를 새로 바꿔주세요
'JavaScript > React' 카테고리의 다른 글
리액트 반복 출력 # map (0) | 2023.02.14 |
---|---|
#동적인 UI 만들기 #state 이용 # onclick Modal (0) | 2023.02.13 |
#component #리액트 컴포넌트 만드는법 # 컴포넌트 사용법 (0) | 2023.02.13 |
#react #html 태그 자동완성 (0) | 2023.02.13 |
React #설치 #사용방법 #리액트시작 (0) | 2023.02.12 |