-
14. React [리액트 애플코딩] JSX문법 , state, state변경함수Java Script & Type Script 2022. 12. 28. 20:55728x90
애플코딩 리액트 강의를 샀다.
이틀 전에도 state관련 TIL을 썼는데 또 쓰는 이유는,
이제야 진짜로 100%이해가 되었기 때문...
사람들이 애플코딩 많이 사길래 나도 궁금해하다가
개인과제하는데, 도저히 안되겠어서 어젯밤에 결제했다....
애플코딩 오늘 하루 공부하고 든 생각은
진작 살걸.. 처음부터 이거만 들을걸
스파르타강의는 들을 수록 코딩은 따라하겠는데 이해도 안가고 ,, 별로다
다시 정리하는 JSX문법과 State
JSX문법
1. class대신 className 이용
2. 변수 넣을 땐 중괄호이용.
전에도 작성했지만, return문을 기준으로 위에는 JS문법 그대로 이용이 가능하고 그 아래로는 JSX로 작성해야한다. 중괄호 없이 그대로 변수 post를 넣으면 단순문자열로 인식된다.
post라는 변수에 "강남 우동 맛집" 란 값을 넣어두고,
h4태그에 집어넣을 때 중괄호를 이용해 가져온다.
블로그 글 제목: 강남 우동 맛집
이라고 화면에 렌더링된다.
3. 태그 내에 style 넣을 땐 style={{스타일명: '값'}}으로 넣는다.
중괄호가 두개인 이유는 {스타일명:'값'} 자체도 JS객체라서이다.
HTML에서는 style="color:red; font-size: 15px"
JSX에서는 style={{color: "red", fontSize: "15px"}}
fontSize인 이유는, JSX내에서 - 데쉬 기호를 못씀. 그래서 camel case로 작성.
return () <----소괄호 안에 html을 짜야하는데, 병렬로 태그 2개 이상은 안됨.
state
자료를 잠깐 저장해두는 변수.
왜 그냥 변수를 안쓰고 state를 쓰냐면,
변수는 갑자기 변경되어도 html에 자동으로 반영이 안된다.
반면 state는 자동리렌더링이 된다.
변동시에 자동으로 html에 반영이 되게 만들고싶으면 state를 쓰면 된다.
자주 변경될 것 같은 html부분을 state로 만들면 좋다 .
useState를 입력하면 위에 자동으로 import가 따라온다.
import { useState} from "react";
이거 그동안 나 다 손으로 쳤는데,,,, 따라오네,,?
let [a,b]=useState("남자 코트 추천")
"남자 코트 추천" 부분이 초기에 들어갈 값이라면 useState형식으로 이렇게 작성해두었다가
대괄호의 앞에 두었던 변수를 가져오면 해당 초기값이 가져와진다.
이건 JS문법인데,
destructuring 이란
배열자료형 num을 a랑 c라는 변수에 빼서 쓸 때,
let num=[1,2]; let a = num[0]; let c = num [1];
이렇게 빼서 쓸 수도 있지만
let num=[1,2]; let [a,c]=[1,2]
이렇게도 빼올 수 있다...
배열로 만들어서 인덱싱을 통해 해당 부분만 보일 수 있도록 코딩.
버튼에 기능개발
좋아요버튼을 만들거다.
let [따봉, c]=useState(0);
저 따봉자리가 0이라는 임시적인 값의 이름이 되고, c가 있는 자리가 state변경함수라는 것이다.
만약 변경함수 쓸 일 없으면 그냥 따봉만 있어도 됨.
저 span태그 내에 onClick Event handler를 넣을것이다.
onClick={함수의 이름}
이런 형태로.
함수 이름이 아니라, 그 함수 이름을 만들지 않고 바로 문법을 넣어버리는 방법도 있다.
저걸 화살표함수로 표현해서
<span onClick={() => {console.log(1); }}>
이렇게도 가능
(화살표 함수...
()=>{} 이게 function(){} 이거랑 같음)
state를 변경하는 법....
1. 등호로 변경 불가.
let a=0; 원래 a는 0이 초기값이였는데 다른 b값이 도출되고나서
a=b+1; JS에서의 이런 등호를 통한 변경은 변수에서만 가능
state에서는 이렇게하면 html리렌더링안된다.
state변경함수를 써야만 변경이 가능하다.
2. let [a,b]에서 b의 위치가 state변경함수이다.
b자리를 따봉변경이라고 두었다. 0이 초기 값이었으며, 버튼을 누르면 따봉변경이라는 state변경함수가 작동하여 1로 변한 값이 렌더링된다.
애플코딩 6강까지의 내용이다.
완즈이 만족하는 중....
❤️
728x90'Java Script & Type Script' 카테고리의 다른 글
17. React [리액트 애플코딩] map매서드 리액트에 적용하기, JSX내에서의 반복문, props 복습하기 (1) 2022.12.30 15. React [리액트 애플코딩] 컴포넌트생성, 동적인 UI만들기 (0) 2022.12.29 13. React [리액트 스파르타 입문 강의] State- part 1 (0) 2022.12.26 12. React 열심히 달리는 중 [리액트 입문 강의 JSX문법 to Props part2] (0) 2022.12.26 11. React 시작 [리액트 입문강의 내용 정리 component part2까지] (0) 2022.12.23