-
15. React [리액트 애플코딩] 컴포넌트생성, 동적인 UI만들기Java Script & Type Script 2022. 12. 29. 00:19728x90
컴포넌트 만들기
1. function을 다른 함수 바깥에 만들고 대문자로 시작하는 컴포넌트를 작명한다.
2. return() 소괄호 안에 표현할 html을 담는다.
여기서, 태그는 두개 이상 병렬할 수 없다.
return ( <div> "Hello" </div> <div> "How are you?" </div>)
이게 안된다는 거다.
return 내에 꼭 html을 병렬로 두개 이상 기입하고싶다면,
<>
<div>
</div>
<div>
</div>
</>
이렇게 아무 의미 없는 <div><div/>를 대신해서 <> </>를 사용할 수 있다.
이를 Fragment문법이라고 한다.
3. 컴포넌트를 표현하기 원하는 위치에 <함수명></함수명>을 입력 (위치는 함수 밖이어야한다)
그리고 <Modal></Modal> 보통은 이렇게 쓰지만
<Modal/>이렇게 하나에 다 담고 닫아도 된다.
컴포넌트 어떨 때 쓰면 좋을까
컴포넌트의 단점은 state를 가져다쓸 때 문제가 생긴다는거다. A함수에 있던 변수는 B에서 가져다 쓰지 못하기 때문이다. component도 함수, state도 함수니까.
Angela라는 컴포넌트 만들어서 HTML로 표현하기.
동적인 UI 만들기
순서는,
1. Html css로 미리 디자인을 완성한다.
2. UI의 현재 상태를 state로 저장. 형식은 자유롭게 원하는대로 해당 상태를 표현이 가능하면 된다.
3. state에 따라 UI가 어떻게 보일지 작성한다.
정말 슬프게도 JSX내 {}중괄호 내에서는 (내가 좋아하는) if 조건문, for 반복문을 못쓴다...😭
삼항연산자는 이용이 가능하니까 삼항연산자로 대체하면 된다.
<div> {modal === true ? <Modal></Modal> : null} </div>
바로 이렇게 삼항연산자로 작동할 수 있게 설치해두고,
이제 modal이라는 state만 true가 되게하면 Modal 컴포넌트가 보여지게 될 것이다.
클릭하면 onClick event handler가 작동하며 modal의 state가 true가 된다.
그럼 이제 Modal컴포넌트가 화면에 보여진다!
동적인 UI구현 성공
다시 한 번 누르면 화면에 보여지지 않게 구현하는 숙제를 받았는데,
나는 JS 알고리즘 문제풀듯이 let count=0 해두고 온클릭시에 +1 씩 해서 count%2===0일 때 보여지게 해야하나? 했으나,
세상에.. ! 느낌표가 이렇게도 쓰이는 것이었다
내일은 리액트 시험이 있다....🤯🤯
728x90'Java Script & Type Script' 카테고리의 다른 글
18. React [리액트 숙련 주차] REDUX 리덕스를 쓰는 이유, Reducer, Dispatch, Action객체 용어 정리, 흐름의 이해 (0) 2023.01.02 17. React [리액트 애플코딩] map매서드 리액트에 적용하기, JSX내에서의 반복문, props 복습하기 (1) 2022.12.30 14. React [리액트 애플코딩] JSX문법 , state, state변경함수 (0) 2022.12.28 13. React [리액트 스파르타 입문 강의] State- part 1 (0) 2022.12.26 12. React 열심히 달리는 중 [리액트 입문 강의 JSX문법 to Props part2] (0) 2022.12.26