Front-End/React(비공)

[React] TypeScript2

리리히히 2024. 3. 21. 09:40
반응형

 

🔎 전체코드 한번에 보기

//index.tsx

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';



const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
  • index.tsx 기본 세팅

 

//App.tsx

import Circle from "./Circle";

function App() {
  return (
    <div>
      <Circle borderColor="black" bgColor="teal" />
      <Circle bgColor="tomato" text="im here" />
    </div>
  );
}

export default App;
  • App.tsx에는 Circle 컴포넌트를 불러와줘야한다.
  • <Circle bgColor="teal" />
    <Circle bgColor="tomato" /> 에서 bgColor는 필수로 들어가야하는 요소이므로 지우면 에러가 뜸

 

//index.js

import styled from "styled-components";

interface ContainerProps {
  bgColor: string;
  borderColor: string;
}
const Container = styled.div<ContainerProps>`
  width: 200px;
  height: 200px;
  background-color: ${(props) => props.bgColor};
  border-radius: 100px;
  border: 3px solid ${(props) => props.borderColor};
`;

interface CircleProps {
  bgColor: string;
  borderColor?: string;
  text?: string;
}

function Circle({bgColor, borderColor, text = "default text"}: CircleProps) {
  return (
    <Container bgColor={bgColor} borderColor={borderColor ?? bgColor } >
      {text}
    </Container>
  );
}

export default Circle
  • Circle.tsx라는 컴포넌트 파일을 src폴더 안에 생성

 


 

🔎 코드 쪼개서 설명

import styled from "styled-components";

interface ContainerProps {
  bgColor: string
}
const Container = styled.div<ContainerProps>`
  width: 200px;
  height: 200px;
  background-color: ${(props) => props.bgColor};
  border-radius: 100px;
`;
  • 스타일 컴포넌트에 관련된 interface

 

interface CircleProps {
  bgColor: string;
  borderColor?: string;
  text?: string;
}
  • Circle props에 관련된 interface
  • bgColor: string;은 필수로 들어가야하는 값이지만,
  • borderColor?: string; 뒤에 물음표가 붙은 경우는 필수 값이 아니기 때문에 작성해 주지 않아도 에러가 뜨지 않음.

 

function Circle({bgColor, borderColor, text = "default text"}: CircleProps) {
  return (
    <Container bgColor={bgColor} borderColor={borderColor ?? bgColor }>
      {text}
    </Container>
  );
}

export default Circle
  • text = "default text"는 text props가 존재하지 않을 경우 default text가 화면에 출력 됨
  • <Container bgColor={bgColor} borderColor={borderColor ?? bgColor}>
    : borderColor가 undefined 된 상태라면 bgColor와 같은 값을 가진다.

 


 

  • interface는 object를 설명해주는 것. 즉, object가 어떻게 보일지 설명
반응형