1) ID
<input>
에서onChange
event 발생
2) event 발생 시handleIdInput
함수 실행const [id, setId] = useState(); const [pw, setPw] = useState(); ~~ onChange={handleIdInput} onChange={handlePwInput}
3)
handleIdInput
는 이벤트를 인자로 받음
4) event가 일어난 요소에 담긴 value 값 (event.target.value
)을 state에 저장
5) 위의 과정을 PW<input>
에도 동일하게 적용const handleIdInput = (e) => { //event 인자 받아서 status에 저장 const idValue = e.target.value; // event가 일어난 value 여기선 문자 setId(idValue); // console.log("id", id); 잘 들어오는 지 검사 }; const handlePwInput = (e) => { const pwValue = e.target.value; setPw(pwValue); // console.log("pw", pw); 잘 들어오는 지 검사 };
(조건 충족시 로그인 버튼 색상 활성화)
<삼항 연산자 조건문>
? a : b ;
➡️ a - 조건문이 참일 때의 값
➡️ b -조건문이 거짓일 때의 값
1) useState 설정
const [id, setId] = useState(); const [pw, setPw] = useState(); const [isValid, setIsValid] = useState(false); // 초기값이 유효하지 않으니 false로 설정
2) 삼항연산자로 조건문 넣어주기
const handleIdInput = (e) => { //event 인자 받아서 status에 저장 const idValue = e.target.value; setId(idValue); idValue.includes("@") && pw.length >= 5 //id 입력할때 pw는 고정이니까 ? setIsValid(true) : setIsValid(false); }; const handlePwInput = (e) => { const pwValue = e.target.value; setPw(pwValue); id.includes("@") && pwValue.length >= 5 // pw입력할때는 id 고정이니까 ? setIsValid(true) : setIsValid(false); };
➡️ ID입력시, PW 입력시 고정값 달라져서 idValue, pwValue 사용
3) button에 적용 시키기
<button style={{ backgroundColor: isValid ? "#4ec5f4" : "#cde9f4" }} //조건이 참이면 진한색, 아니면 연한색
<Array.map>
배열의 값들을 오름차순으로 접근해 새로운 값을 정의하고 신규 배열을 만들어 반환함.
1) Feed.js로 피드 항목 분리
2) 고정 댓글 생성function Feed() { const [comment, setComment] = useState(); //변경되는 댓글을 새로 넣어주기 const [id, setId] = useState(1); //초기값을 넣어줘야 밑에 +1 이 찍힘 const [commentArray, setCommentArray] = useState([ // 배열안에 객체로 관리 { id: 0, content: "완전 맛있어 보인다", }, ]);
3) 신규 댓글 생성 - 1. 댓글 입력 창에 useState 적용하여 가져오기
const addComment = () => { setId(id + 1); const newComment = { id: id, content: comment, }; setCommentArray([...commentArray, newComment]); //comment spray };
<div className="feed-comment-list padiing-10"> {commentArray.map((comment) => { //map 사용시에 식별할 수 있는 key가 필요 return <li key={comment.id}>{comment.content}</li>; })}
<div className="feed-comment-write"> <input className="commentinput" type="text" placeholder="댓글 달기..." onChange={(e) => { setComment(e.target.value); }} />
3) 신규 댓글 생성 - 2.useRef 사용 (onChange함수 사용 안함)
import { useState, useRef } from "react";
function Feed() { const [comment, setComment] = useState(); const [id, setId] = useState(1); const value = useRef(); //value를 참조하고 싶은 tag에 거는 것
const addComment = () => { setId(id + 1); const newComment = { id: id, content: value.current.value, // value : useRef를 담은 값, currnet.value: 해당 태그의 value }; setCommentArray([...commentArray, newComment]); };
<div className="feed-comment-write"> <input className="commentinput" type="text" placeholder="댓글 달기..." ref={value} />