더보기
Detail.js

하트

좋아요 1

댓글수 2

기본댓글1 내용

기본댓글2 내용



훅스 useState 



App.js에 Detail.js



state
1 comment 배열 2개
2 likeCount



하트를 클릭하면 좋아요 카운트를 올리고 useEffect를 이용해서 색깔이 변하고

좋아요 수가 2로 변함



나중에 댓글을 쓰면 부모의 state 값을 바꿔야한다

 

 

import React, { useState, useRef, useEffect } from "react";
import emptyimg from "./img/empty_heart.png";
import fillimg from "./img/fill_heart.png";

const Detail = () => {
  const [like, setLike] = useState(0);
  const [count, setCount] = useState(2);
  const [nowImg, setNowImg] = useState(emptyimg);
  const img = useRef();

  useEffect(() => {
    console.log("use");
    img.current.src = nowImg;
  }, [like]);

  const fill = () => {
    setLike(like + 1);
    setNowImg(fillimg);
  };

  return (
    <div>
      <div>
        <img onClick={fill} ref={img} />
      </div>
      <div>좋아요{like}</div>
      <div>댓글수{count}</div>
      <div>댓글1</div>
      <div>댓글2</div>
    </div>
  );
};

export default Detail;

 

 

 

 

참고사항

https://20200302wc.tistory.com/474

 

리액트 숙제

https://github.com/jg20228/ReactHooksHomework import React, { useState, useEffect, useRef } from "react"; import logo2 from "./img/logo2.png"; import logo1 from "./img/logo.jpg"; const Detail2 = ()..

20200302wc.tistory.com

 

+ Recent posts