24.08.26 Day34

최지원·2024년 8월 26일

리액트

1) npm 모듈 초기화
명령어 : npm init

2) npx create-react-app 프로젝트명

  • npx : npm과 달리 해당하는 모듈이 없으면, 설치 후 실행
           create-react-app이 없으면 설치 후 실행
  • CRA : 노드 기반의 리액트 프로젝트 템플릿을 만들어주는 모듈
  • 명령어 : npx create-react-app first-app

3) 프로젝트 시작
cd first-app
npm start

Comment

  • Comment.jsx 파일
import React from "react";

const styles = {
  wrapper: {
    margin: 8,
    padding: 8,
    display: "flex",
    flexDirection: "row",
    border: "1px solid grey",
    borderRadius: 16,
  },
  imageContainer: {},
  image: {
    width: 50,
    height: 50,
    borderRadius: 25,
  },
  contentContainer: {
    marginLeft: 8,
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
  },
  nameText: {
    color: "black",
    fontSize: 16,
    fontWeight: "bold",
  },
  commentText: {
    color: "black",
    fontSize: 16,
  },
};

function Comment(props) {
  return (
    <div style={styles.wrapper}>
      <div style={styles.imageContainer}>
        <img
src="https://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png"
          style={styles.image}
        />
      </div>
      <div style={styles.contentContainer}>
        <span style={styles.nameText}>{props.name}</span>
        <span style={styles.commentText}>{props.comment}</span>
      </div>
    </div>
  );
}

export default Comment;
  • index.js파일
import React from 'react';
import ReactDOM from 'react-dom/client';
import Comment from './5-props/Comment';

const root = ReactDOM.createRoot(document.getElementById('root'));

// 5-props/Coment
root.render(<Comment />);

Notification

  • Notification.jsx
import React from "react";

const styles = {
  wrapper: {
    margin: 8,
    padding: 8,
    display: "flex",
    flexDirection: "row",
    border: "1px solid grey",
    borderRadius: 16,
  },
  messageText: {
    color: "black",
    fontSize: 16,
  },
};

class Notification extends React.Component {
  // 생성자 : 객체생성시 자동으로 한번 호출(초기화)
  constructor(props) {
    super(props); //부모클래스의 생성자함수를 호출해준다.

    //this : 자신의 현재 객체
    this.state = {};
  }
  //컴퍼넌트가 마운트(생성)시 호출
  componentDidMount() {
    console.log(`${this.props.id} componentDidMount() called.`);
  }
  //컴퍼넌트가 데이터가 수정되었거나 부모컴퍼넌트가 re-render되었을 때
  componentDidUpdate() {
    console.log(`${this.props.id} componentDidUpdate() called.`);
  }
  //컴퍼넌트가 언마운트(소멸)시 호출
  componentWillUnmount() {
    console.log(`${this.props.id} componentWillUnmount() called.`);
  }
  render() {
    console.log(`${this.props.id} render() called.`);
    return (
      <div style={styles.wrapper}>
        <span style={styles.messageText}>{this.props.message}</span>
      </div>
    );
  }
}

export default Notification;
  • NotificationList.jsx
import React from "react";
import Notification from "./Notification";

const reservedNotifications = [
  {
    id: 1,
    message: "안녕하세요. 오늘 일정 알려드립니다.",
  },
  {
    id: 2,
    message: "이벤트 공지 드립니다.",
  },
  {
    id: 3,
    message: "회의가 곧 시작합니다.",
  },
];

let timer;

class NotificationList extends React.Component {
  constructor(props) {
    super(props);

    this.state = { notifications: [] };
  }
  componentDidMount() {
    const { notifications } = this.state;
    timer = setInterval(() => {
      if (notifications.length < reservedNotifications.length) {
        const index = notifications.length;
        notifications.push(reservedNotifications[index]);
        this.setState({ notifications: notifications });
      } else {
        this.setState({
         // notifications: [],
        });
        clearInterval(timer);
      }
    }, 1000);
  }
  componentWillUnmount() {
    if (timer) {
      clearInterval(timer);
    }
  }
  render() {
    return (
      <div>
        {this.state.notifications.map((notification) => {
          return (
            <Notification
              key={notification.id}
              id={notification.id}
              message={notification.message}
            />
          );
        })}
      </div>
    );
  }
}

export default NotificationList;
  • index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import NotificationList from './6-state/NotificationList';

const root = ReactDOM.createRoot(document.getElementById('root'));

// 6-state/NotificationList
root.render(<NotificationList />);

Counter

리액트 훅

  • 리액트 함수에 갈고리(Hook)을 걸어 원하는 시점의 정해진 함수를 실행하도록 해주는 함수
  • 항수형 컴퍼넌트에서 상태, 생명주기, 메모라이즈 등과 같은 기능을 지원


  • Counter.jsx
import React, {useState, useEffect} from "react";

// useEffect : 함수형 컴퍼넌트에서 생명주기 함수 지원
function Counter(props){
    const [count,setCount] = useState(0);

    // componentDidMount(), componentDidUpdate()와 비슷하게 동작
    // didUpdate()함수 호출 : 상태변수(count) 변경될 때 Re-Render
    //                        부모의 상태변수가 변경될 때 ReRender
    useEffect(() => {
        console.log(`${count}번 클릭했습니다.`);
    });

    return (
        <div>
            <p>{count}번 클릭했습니다.</p>
            <button onClick={() => setCount(count +1)}>클릭하세요</button>
        </div>
    );
}

export default Counter;

export default Counter;
  • index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import Counter2 from './7-hook/Counter2';

const root = ReactDOM.createRoot(document.getElementById('root'));

// 7-hook/Counter
root.render(<Counter2 />);

0개의 댓글