Loading...
본문 바로가기
👥
총 방문자
📖
0개 이상
총 포스팅
🧑
오늘 방문자 수
📅
0일째
블로그 운영

여러분의 방문을 환영해요! 🎉

다양한 개발 지식을 쉽고 재미있게 알려드리는 블로그가 될게요. 함께 성장해요! 😊

코딩 정보/React

[React] 주요 개념 알아보기

by 꽁이꽁설꽁돌 2024. 6. 21.
728x90
반응형

목차

     

     

     

    index.js 리액트 앱의 진입점

     

    여기의 root에 내용이 담기게 된다.

     

     

    커스텀 컴포넌트 규칙

    컴포넌트 이름은 대문자로 시작해야 한다.

    ->다른 개발자가 만든 커스텀 컴포넌트와 리액트 내장된 컴포넌트를 구분을 하기 위해서이다.

     

     

    동적인 값 출력하기

    import React from "react";
    
    const greetArray = ["hello", "hi", "okay"];
    
    
    function getRandomInt(num) {
      let newNumber= Math.floor(Math.random() * num) ;
      return newNumber;
    }
    
    //이런식으로 중괄호에 넣어주면 된다.
    function Lecture1() {
      return <div>{greetArray[getRandomInt(3)]}</div>;
    }
    
    export default Lecture1;

     

    동적인 HTML속성 설정 / 이미지 업로드

    //이런식으로 이미지를 불러올 때 배포 시 유실을 막을 수 있다
    //최적화 단계에 필요하다
    import React from "react";
    import Img from '../public/logo192.png'
    
    function Lecture1() {
      return <img src={Img} alt="Img" />;
    }
    
    export default Lecture1;

     

    props 활용하기

    import React from "react";
    import Img from "../public/logo192.png";
    
    
    function Concept({ toStudy, toDo, grade }) {
      return (
        <div>
          <div>Grade: {grade}</div>
          <div>To Do: {toDo}</div>
          <div>To Study: {toStudy}</div>
        </div>
      );
    }
    
    //스프레드 연산자 활용
    function Lecture1() {
      const myList: List[] = [
        {
          toStudy: "css",
          grade: 1,
          toDo: "playing",
        },
        {
          toStudy: "html",
          grade: 2,
          toDo: "soccer",
        },
      ];
      return (
        <div>
          <Concept {...myList[0]} />
          <Concept {...myList[1]} />
            {/* 아래 것은 비효율적 */}
          <Concept
            toStudy={myList[0].toStudy}
            toDo={myList[0].toDo}
            grade={myList[0].grade}
          />
        </div>
      );
    }
    
    export default Lecture1;

     

     

    props children 사용

    import React from "react";
    
    const buttons = ["css", "html", "js"];
    
    function ButtonList(props) {
      return (
        <div>
          {props.children}
          {buttons.map((item, index) => (
            <button type="button" key={index}>
              {item}
            </button>
          ))}
        </div>
      );
    }
    
    export default ButtonList;
    
    
     //버튼 목록이 자식요소로 들어가게 된다.
     <ButtonList>버튼 목록</ButtonList>

     

     

    이벤트 처리하기

    import React from "react";
    
    const buttons = ["css", "html", "js"];
    
    function ButtonList(props) {
    
      function clickEvent(){
        console.log("hello");
      }
      //이벤트에 함수 전달할때 clickEvent()로 전달하면 함수가 바로 실행됨
      //따라서 함수명을 전달해주어야 함
      return (
        <div>
          {props.children}
          {buttons.map((item, index) => (
            <button onClick={clickEvent} type="button" key={index}>
              {item}
            </button>
          ))}
        </div>
      );
    }
    
    export default ButtonList;
    
    
    
    //아래와 같이 함수 전달 가능
    import React from "react";
    
    const buttons = ["css", "html", "js"];
    
    function ButtonList({children, onSelect}) {
      function clickEvent() {
        console.log("hello");
      }
      //이벤트에 함수 전달할때 clickEvent()로 전달하면 함수가 바로 실행됨
      //따라서 함수명을 전달해주어야 함
      return (
        <div>
          {children}
          {buttons.map((item, index) => (
            <button onClick={clickEvent} type="button" key={index}>
              {item}
            </button>
          ))}
          //이런식으로 해주어 됨
          <button onClick={()=> onSelect()}>special</button>
        </div>
      );
    }
    
    export default ButtonList;

     

    React Hook

    import React from "react";
    import { useState } from "react";
    const buttons = ["css", "html", "js"];
    
    //useState는 함수안에서 최상단에 위치해야 함
     //리액트에서 ui가 변한 것을 알려주며 리랜더링 됨
    function ButtonList({ children }) {
      const [message, setMessage] = useState("first");
    
      function clickEvent(message) {
        setMessage(message);
      }
     
     
      return (
        <div>
          {children}
          {buttons.map((item, index) => (
            <button onClick={() => clickEvent(item)} type="button" key={index}>
              {item}
            </button>
          ))}
          {message}
        </div>
      );
    }
    
    export default ButtonList;

     

    조건적 콘텐츠 렌더링

    import React from "react";
    import ButtonList from "./ButtonList";
    import { useState } from "react";
    
    
    const CORE_CONCEPTS = [
      {
        title: "Components",
        description:
          "The core UI building block - compose the user interface by combining multiple components.",
      },
      {
        title: "JSX",
        description:
          "Return (potentially dynamic) HTML(ish) code to define the actual markup that will be rendered.",
      },
      {
        title: "Props",
        description:
          "Make components configurable (and therefore reusable) by passing input data to them.",
      },
      {
        title: "State",
        description:
          "React-managed data which, when changed, causes the component to re-render & the UI to update.",
      },
    ];
    
    //방법 1
    function Lecture1() {
      const [description, setDescription] = useState(null);
    
      function randomMessage() {
        let randomNum = Math.floor(Math.random() * 3);
        setDescription(CORE_CONCEPTS[randomNum].description);
      }
    
      return (
        <div>
          {description === null ? "empty" : description}
          <button onClick={randomMessage}>랜덤 메세지</button>
        </div>
      );
    }
    
    export default Lecture1;
    
    
    //방법 2
    function Lecture1() {
      const [description, setDescription] = useState(null);
    
      function randomMessage() {
        let randomNum = Math.floor(Math.random() * 3);
        setDescription(CORE_CONCEPTS[randomNum].description);
      }
    
      return (
        <div>
          {!description && "empty"}
          {description &&  description}
          <button onClick={randomMessage}>랜덤 메세지</button>
        </div>
      );
    }
    
    export default Lecture1;

     

    반응형