티스토리 뷰

// 동물 이미지 뷰어 만들기

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/