티스토리 뷰
// 동물 이미지 뷰어 만들기
import './App.css'
import React, { Component } from "react";
import images from "./imageData";
import Button from "./components/Button";
class App extends Component{
state={
index : 0
}
decreaseIndex = () =>{
const nextIndex = this.state.index - 1
this.setState({ index: (nextIndex < 0) ? images.length -1 : nextIndex}) // index 값이 0보다 작으면, 이미지 배열의 마지 막 사진을 선택한다(images.length - 1)
}
increaseIndex = () =>{
const nextIndex = this.state.index + 1
this.setState({ index: (nextIndex > images.length -1) ? 0 : nextIndex}) // index 값이 이미지 배열의 마지막 사진 보다 크면, 첫번째 사진으로 이동한다.
render(){
const { index } = this.state
const { increaseIndex, decreaseIndex } = this // 이렇게 하면 this.decreaseIndex, this.IncreaseIndex 와 같이 작성하지 않아도 된다.
images : images 배열
images[index] : images배열의 index번째 객체
images[index].src : images배열의 index번째 객체의 속성(src)
const path = images[index].src
const title = images[index].title
return(
<div className="App">
<div className="img-container">
<img src={path} alt={title} />
</div>
<div className="control-btns">
<Button handleClick={decreaseIndex}>이전</Button> {/* Button 컴포넌트 재사용 */}
<Button handleClick={increaseIndex}>다음</Button> {/* Button 컴포넌트 재사용 */}
</div>
</div>
)
}
}
export default App
정리
1. JSX 문법 안에서는 IF문을 사용할 수 없으므로, 삼항 연산자를 사용한다.
decreaseIndex = () =>{
const nextIndex = this.state.index - 1
this.setState({ index: (nextIndex < 0) ? images.length -1 : nextIndex})
}
increaseIndex = () =>{
const nextIndex = this.state.index + 1
this.setState({ index: (nextIndex > images.length -1) ? 0 : nextIndex})
}
사진의 맨 끝에서 다음 버튼을 누르면 맨 처음 사진으로 이동, 사진의 맨 처음에서 이전 버튼을 누르면 맨 마지막 사진으로 이동한다. 삼항연산자 이해하기.
2. 구조분해
const { increaseIndex, decreaseIndex } = this // 이렇게 하면 this.decreaseIndex, this.IncreaseIndex 와 같이 작성하지 않아도 된다.
this.increaseIndex, this.decreaseIndex를 구조분해 하면, 해당 스코프에서 this를 제외하여 사용할 수 있다.
3. 대괄호 표기법
images가 배열이고 그 안에 값 들이 객체일 때 : ex) images = [ {key:value}, {key:value}....]
images[index]는 index번째의 객체
images[index].key는 index번째 객체의 key 값 을 조회할 수 있다.
코드 출처 : 선생님 블로그 https://syleemomo.tistory.com/
'개발공부 > React' 카테고리의 다른 글
#React 이미지 경로 문제 (0) | 2024.05.17 |
---|---|
React_정렬, 검색 기능 만들기 (0) | 2023.09.10 |
React_사이드바 만들기 (0) | 2023.09.07 |
React_하위 컴포넌트로 props가 전달되는 과정 (0) | 2023.09.07 |
React_setState : 원본데이터 변경하지 말고 새로운 배열을 생성하자 (0) | 2023.09.06 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- JSX
- 태스크큐
- 전역변수
- 함수
- 미들웨어위치
- 대괄호표기법
- 문자열
- universal rendering
- 객체속성 추가 삭제
- Props
- 조대곤교수님
- 배열내특정요소찾기
- 상속
- 리액트 이미지경로
- .then()
- unexpected character
- 비동기
- .catch()
- .finally()
- promise
- 객체리터럴
- 프로토타입 체이닝
- unique "key" prop.
- react
- 에이블스쿨2일차
- cors위치
- null과 undefined
- 동등비교연산자
- 함수형코딩
- 머리아프다..
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
글 보관함