[TIL] 230612

이세령·2023년 6월 12일
0

TIL

목록 보기
25/118

React

  • 리액트 CRA 명령어
yarn create react-app 폴더명
  • 실행 명령어
yarn start
  • 절대경로를 사용하기 위해
    jsconfig.json 파일 생성 및 아래 코드 작성
{
    "compilerOptions": {
        "baseUrl": "src"
    },
    "include": ["src"]
}
  • js사용하기
    React문법에서 js를 사용하려면 {}로 감싸주면 사용할 수 있다.
export default function App() {
  const number = 1;

  const pTagStyle = {
    color: "red",
  };

  return (
    <div className='test-class'>
      <p style={pTagStyle}>안녕하세요. 리액트 입니다.</p>
      {/* 주석 */}
      {/* 삼항 연산자 */}
      <p style={{
        color: 'red',
      }}>{number > 10 ? number +'은 10보다 크다':number + '은 10보다 작다.'}</p>
    </div>
  )
}

Props

기본적으로 상위 -> 하위 방식으로 Props(데이터)를 전달 가능하다.
하위 컴포넌트가 데이터를 받아 사용하고 싶을 때, 매개변수로 props를 전달받아 사용한다.

상위 컴포넌트가 변수 = {작성한 js코드}
console.log(props)를 하위에서 실행해보면 어떤 값이 담겨있는지 확인할 수 있다.

import React from 'react'

// 자식 컴포넌트 
function Child(props) {
  console.log("props",props);
  return <div>나는 {props.grandfatherName}의 손자에요</div>;
}
// 엄마 컴포넌트 
function Mother(props) {
  console.log(props);
  const name = "흥부인";
  const grandfatherName = props.grandfaName;
  return <Child grandfatherName={grandfatherName} />;
}

// 할아버지 컴포넌트 
function GrandFather() {
  const gName = "할아버지"
  return <Mother grandfaName={gName}/>;
}

function App(){
  return <GrandFather></GrandFather>;
}

export default App;

children props

상위 -> 하위로 데이터를 보낼 수 있고 이때, 담겨져있는 데이터의 key는 children 이다.
<컴포넌트>children에서 보낼 값</컴포넌트>
태그 내에있는 text값을 마음대로 수정할 수 있다.

Default props

초기값 지정해주는 법

컴포넌트.defaultProps= {
	key: value
}

props의 개념은 상속과 js를 다루며 데이터를 매개변수로 넘겨받는 연습을 했다면 이해하는데에 크게 어렵지는 않을 것 같다.
function 함수(props) -> 받을 데이터

profile
https://github.com/Hediar?tab=repositories

0개의 댓글