[React] state로 이벤트 처리하기

daun·2022년 6월 7일
0

[오답노트]

목록 보기
13/26

input에 있는 Value값 받아오기

import React, { useState } from "react";
import "./styles.css";
function SelectExample() {
  const [choice, setChoice] = useState("apple");
  const fruits = ["apple", "orange", "pineapple", "strawberry", "grape"];
  const options = fruits.map((fruit) => {
    return <option value={fruit}>{fruit}</option>;
  });
  console.log(choice);
  const handleFruit = (event) => {
    //TODO : select tag 가 정상적으로 작동하도록 코드를 완성하세요.
    setChoice(event.target.value)
  };
  return (
    <div className="App">
      <select onChange={handleFruit}>{options}</select>
      <h3>You choose "{choice}"</h3>
    </div>
  );
}
export default SelectExample;

popup state 바꿔주기

import React, { useState } from "react";
import "./styles.css";
function App() {
  const [showPopup, setShowPopup] = useState(false);
  const togglePopup = () => {
    // Pop up 의 open/close 상태에 따라
    // 현재 state 가 업데이트 되도록 함수를 완성하세요.
    setShowPopup(!showPopup)
  };
  return (
    <div className="App">
      <h1>Fix me to open Pop Up</h1>
      {/* 버튼을 클릭했을 때 Pop up 의 open/close 가 작동하도록
          button tag를 완성하세요. */}
      <button className="open" onClick={togglePopup}>Open me</button>
      {showPopup ? (
        <div className="popup">
          <div className="popup_inner">
            <h2>Success!</h2>
            <button className="close" onClick={togglePopup}>
              Close me
            </button>
          </div>
        </div>
      ) : null}
    </div>
  );
}
export default App;

Tweets - BareMinimum

<Tweets.js>
import React, { useState } from "react";
import Footer from "../Footer";
import Tweet from "../Components/Tweet";
import "./Tweets.css";
import dummyTweets from "../static/dummyData";
const Tweets = () => {
  //useState 사용해서 state 만들기
  const [user, setUser] = useState("parkhacker");
  const [msg, setMsg] = useState("");
  const [tweets, setTweets] = useState(dummyTweets);
  const [counter, setCounter] = useState(tweets.length);
  const handleButtonClick = (event) => {
    //버튼클릭->event로 들어온 정보를 통해->tweet라는 새로운 객체 생성
    const tweet = {
      id: dummyTweets.length,
      username: user,
      picture:
        "https://upload.wikimedia.org/wikipedia/ko/thumb/8/81/Spongebob_4795.jpg/230px-Spongebob_4795.jpg",
      content: msg,
      createdAt: new Date().toLocaleDateString("ko-kr"),
      updatedAt: new Date().toLocaleDateString("ko-kr"),
    };
    // 객체를 다 만들면, setTweets통해-> 새로운 배열생성->tweet를 상단에 넣고 그 전에 있던 ...tweets 가져온다.
    const newTweets = [tweet, ...tweets];
    setTweets(newTweets);
    //setCounter통해, counter +1 증가 시킨다.
    setCounter(counter + 1);
  };
  const handleChangeUser = (event) => {
    setUser(event.target.value);
  };
  const handleChangeMsg = (event) => {
    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"
                  defaultValue="parkhacker"
                  placeholder="your username here.."
                  className="tweetForm__input--username"
                  // input 값이 변할때마다 -> onChange 변화감지-> {handleChangeUser} 함수실행->setUser를 통해 user값 변경
                  onChange={handleChangeUser}
</input>
                <textarea
                  className="tweetForm__input--message"
                  // text 값이 변할때마다 -> onChange 변화감지-> {handleChangeMsg} 함수실행->setMsg를 통해 msg값을 변경
                  onChange={handleChangeMsg}
</textarea>
              </div>
              <div className="tweetForm__count" role="status">
                <span className="tweetForm__count__text">
                  total : {counter}
                </span>
              </div>
            </div>
            <div className="tweetForm__submit">
              <div className="tweetForm__submitIcon"></div>
              <button
                className="tweetForm__submitButton"
                // 버튼클릭 할때마다 -> onClick 변화감지-> {handleButtonClick} 함수실행->setCounter 통해 counter값을 변경
                onClick={handleButtonClick}>
                Tweet
              </button>
            </div>
          </div>
        </div>
      </div>
      <div className="tweet__selectUser"></div>
      <ul className="tweets">
        {tweets.map((el) => {
          // tweets-> 객체안 요소(tweet)하나씩 보여주기
          return <Tweet tweet={el} />;
        })}
      </ul>
      <Footer />
    </React.Fragment>
  );
};
export default Tweets;
profile
Hello world!

0개의 댓글