본문 바로가기
Frontend/React.js

React - 이벤트를 사용하여 state 변경

by Hyeonlog 2022. 12. 21.
728x90

이벤트 사용

  1. 어떤 이벤트를 watch 할 지 결정
  2. 함수를 생성, event handler callback function
  3. naming convention : handle_event name → community convention
  4. pass prop to plain element
  5. pass function using a valid event name!
  6. → 헷갈리는 경우 react docs를 참고하여 정확한 이벤트 이름을 보낼 것
  7. pass reference to function
 const doGreeting = () => {
      return 'Hi there'
    }
<button onClick={doGreeting}>Hi!</button> 
console.log('1번: ', doGreeting) -> 함수를 호출 하지않음
console.log('2번: ', doGreeting()) -> 함수를 바로 호출함

상황에 따라 다르지만 대부분 이벤트의 경우 해당 컴포넌트를 렌더링했을 때가 아닌 유저의 행동이 발생했을 때
실행시키게 되므로 1번으로 진행한다.

State

유저의 사용에따라 데이터가 바뀜, 바뀐데이터는 리액트가 자동으로 업데이트하여 화면에 보여줌
one-and-only way
화면에 보여주고 싶은경우 useState를 사용하면됨

import './App.css'
import {useState} from 'react'; //useState를 사용하기 위해서 import
import AnimalShow from './AnimalShow';

function getRandomAnimal(){
  const animals = ['bird', 'cat', 'cow', 'dog', 'gator', 'horse']

  return animals[Math.floor(Math.random() * animals.length)]
}

function App() {
  // const [count, setCount ] = useState(0) 
	// array destructing state + setter, state 를 바로 변경하는 경우는 절대없음
  // setter 함수가 실행되면 리액트는 컴포넌트를 리렌더링함

  const [animals, setAnimals] = useState([])

  const handleClick = () =>{
    // setCount(count + 1)

    setAnimals([...animals, getRandomAnimal()])

    // animals.push(getRandomAnimal()) // modifies state! 
  }

  const renderedAnimals = animals.map((animal, index)=>{
    return <AnimalShow type={animal} key={index}/>
  }) // map을 사용하여 prop을 수정하여 보낼 수 있음

return <div className='app'>
  <button onClick={handleClick}>Add animal</button> 
  <div className='animal-list'>
    {renderedAnimals}
  </div>
  {/* <p>count : {count}</p> */}
  {/* onClick={() => console.log('button was clicked')} 와 동일함
  간단한 함수를 작성하는 경우 따로 분리하는 것보다 편리함*/}
</div>
}
export default App

function AnimalShow({type}) { //부모컴포넌트에서 보낸 prop을 destructing해서 바로 받을 수 있음
  const [clicks, setClicks] = useState(0)
  const handleClick = () =>{
    setClicks(clicks + 1)
  }
  return (
    <div className='animal-show' onClick={handleClick}>
      <img className='animal' alt='animals' src={svgMap[type]} width="100"/>
      <img 
      className='heart'
        alt="heart" 
        src={heart}
        style={{ width:10 + 10 * clicks + 'px' }}/>
    </div>)
}
export default AnimalShow

 

유데미 Modern React with Redux [2023 Update] 를 듣고 정리한 글입니다.

 

이전 강의 정리 글

React - reusable components(with. bulma.css)

React - jsx(JavaScript Xml)

728x90
반응형