Section 2 React Twittler State & Props 과제

44523·2023년 1월 27일

State와 Props

State
살면서 변할 수 있는 값
컴포넌트의 사용 중 컴포넌트 내부에서 변할 수 있는 값
state는 하위 컴포넌트에서도 존재할 수 있다
ex ) 나이, 현재 사는 곳, 취업 여부, 결혼/연애 여부

How to use State

useState

import { useState } from "react";

function CheckboxExample() {
// 새로운 state 변수를 선언하고, 여기서는 이것을 isChecked 라 부르겠습니다.
  const [isChecked, setIsChecked] = useState(false);
}

function CheckboxExample() {
  // 1번 코드를 풀어쓰면
  const [isChecked, setIsChecked] = useState(false); // 1번

  //...

  // 2번 코드와 같습니다.
  const stateHookArray = useState(false); // 2번
  const isChecked = stateHookArray[0];
  const setIsChecked = stateHookArray[1];
}

const [state 저장 변수, state 갱신 함수] = useState(상태 초기 값);

function CheckboxExample() {
  const [isChecked, setIsChecked] = useState(false);
  // const [state 저장 변수, state 갱신 함수] = useState(state 초깃값);

isChecked : state를 저장하는 변수
setIsChecked : state isChecked 를 변경하는 함수
useState : state hook
false : state 초깃값

1
{isChecked ? "Checked!!" : "Unchecked"}

Props
외부로부터 전달받은 값
ex ) 이름, 성별
컴포넌트의 속성을 의미하며 외부로부터 전달받은 변하지 않는 값.
부모 컴포넌트로 부터 전달받은 값
컴포넌트가 최초 렌더링 될 때 화면에 출력하고자 하는 데이터를 담은 초깃값으로 사용 가능
어떤 타입의 값을 넣어도 전달할 수 있도록 객체의 형태
읽기전용 객체

How to use props

  1. 하위 컴포넌트에 전달하고자 하는 값(data)과 속성을 정의한다
  2. props를 이용하여 정의된 값과 속성을 전달한다
  3. 전달받은 props를 렌더링한다
function Parent() {
  return (
    <div className="parent">
      <h1>I'm the parent</h1>
      <Child text={"I'm the eldest child"} />
      <Child />
    </div>
  );
}

function Child(props) {
  console.log("props : ", props);
  return (
    <div className="child">
      <p>{props.text}</p>
    </div>
  );
  

props.children 방법

function Parent() {
  return (
    <div className="parent">
        <h1>I'm the parent</h1>
        <Child>I'm the eldest child</Child>
    </div>
  );
};

function Child(props) {
  return (
    <div className="child">
        <p>{props.children}</p>
    </div>
  );
};

state-props 과제

import React, { useState } from 'react'; // Keep : React, 컴마의 의미는? 
import Footer from '../Footer';
import Tweet from '../Components/Tweet';
import './Tweets.css';
import dummyTweets from '../static/dummyData';

const Tweets = () => {
  const [addTweet, addtweet] = useState(dummyTweets);
  const [username, setUsername] = useState("");
  const [msg, setMsg] = useState("");
    

    
  const handleButtonClick = (event) => {
    const tweet = {
      id: Date.now(),
      username: username,
      picture: `https://randomuser.me/api/portraits/women/${parseInt(Math.random() * (Number(98) - Number(1) + 2))}.jpg`,
      content: msg,
      createdAt: new Date(),
      updatedAt: new Date(),
    };

      addtweet([tweet].concat(addTweet))

    // React 컴포넌트는 state가 변경되면 새롭게 호출되고, 리렌더링 됩니다.

    // TODO : Tweet button 엘리먼트 클릭시 작동하는 함수를 완성하세요.
    // 트윗 전송이 가능하게 작성해야 합니다.
  };

  const handleChangeUser = (event) => {
    // TODO : Tweet input 엘리먼트에 입력 시 작동하는 함수를 완성하세요.      
    setUsername(event.target.value);
  };

  const handleChangeMsg = (event) => {
    // TODO : Tweet textarea 엘리먼트에 입력 시 작동하는 함수를 완성하세요.
    
      setMsg(event.target.value);
  };
    
  return (
    <React.Fragment>
      <div className="tweetForm__container">
        <div className="tweetForm__wrapper">
          <div className="tweetForm__profile">
            <img src="https://randomuser.me/api/portraits/men/98.jpg" />
          </div>
          <div className="tweetForm__inputContainer">
            <div className="tweetForm__inputWrapper">
              <div className="tweetForm__input">
                <input
                  type="text"                                  
                  placeholder="your username here.."
                  className="tweetForm__input--username"
                  onChange={handleChangeUser}
                  value={username}
                ></input>
               {/* TODO : 트윗을 작성할 수 있는 textarea 엘리먼트를 작성하세요.
               유어클래스 참조*/}
               <textarea
                  placeholder="여기는 텍스트 영역입니다."
                  className="tweetForm__input--message"
                  onChange={handleChangeMsg}
                  value={msg}
                ></textarea>
               
              </div>
              <div className="tweetForm__count" role="status">
                <span className="tweetForm__count__text">'total: ' + {addTweet.length} </span>
              </div>
            </div>
            <div className="tweetForm__submit">
              <div className="tweetForm__submitIcon"></div>
              <button onClick={handleButtonClick} className="tweetForm__submitButton">Button</button>
              {/* TODO : 작성한 트윗을 전송할 수 있는 button 엘리먼트를 작성하세요. */}
            </div>
          </div>
        </div>
      </div>
      <div className="tweet__selectUser"></div>
      <ul className="tweets">
        {/* TODO : 하나의 트윗이 아니라, 주어진 트윗 목록(dummyTweets) 갯수에 맞게 보여줘야 합니다. */}
        {/*<Tweet tweet={dummyTweets[0]} />*/}
        {addTweet.map((tweet) => <Tweet tweet={tweet} key={tweet.id} />)}
      </ul>                  
      <Footer />
    </React.Fragment>
  )
}

0개의 댓글