FE

TS - defaultProps 사용법

<zinny/> 2022. 5. 12. 23:58
728x90
import React from "react";
import styled from 'styled-components';

interface ButtonProps {
  text: boolean
  children: any
  _onClick: () => void
  margin: string
  width: string
  height: string
  padding: string
  active: boolean
  bg: string
  color: string
  br: string
  top: string
  left: string
}
//interface에다 프롭스의 타입을 전부 정의 해줘야 한다. 

const Button = ({ text, _onClick, children, margin, width, padding, height, active, bg, color, br, top, left }: ButtonProps) => {
  const styled = { margin, width, height, padding, bg, color, br, top, left }
  //스타일만 따로 모아서 만들어놔야함 
  return <React.Fragment>
    <Btn
      {...styled}
      onClick={_onClick}
    >
      {text ? text : children}
    </Btn>
  </React.Fragment>;
};
Button.defaultProps = {
  text: true,
  children: null,
  _onClick: () => { },
  margin: '',
  width: '',
  height: '',
  padding: '',
  bg: '',
  color: '',
  br: '',
  top: '',
  left:''
}


const Btn = styled.button`
  background-color: ${(props: any) => (props.bg==='red' ? '#DF0000' : '#fff')};;
  //타입스크립트에선 props가 뭔지 명시 해줘야 함 
  border: 0;
  ${(props: any) => (props.br ? `border-radius:${props.br};` : '')};
  //있을때도 있고 없을때도 있기 때문에 이런식으로 표현 해준다. 
  box-shadow: 0 1px 1px 1px rgba(113, 113, 113, 0.3);
  //바뀌지 않는 값들은 직접 표현 가능 
  color: ${(props:any)=>(props.color==='black'?'#000000':'#fff')};
  ${(props: any) => (props.width ? `width:${props.width};` : '')};
  ${(props: any) => (props.margin ? `margin:${props.margin};` : '')};
  ${(props: any) => (props.height ? `height:${props.height};` : '')};
  ${(props: any) => (props.padding ? `padding:${props.padding};` : '')};
  cursor: pointer;
  position: absolute;
  ${(props: any) => (props.top ? `top:${props.top};` : '')};
  ${(props: any) => (props.left ? `left:${props.left};` : '')};
`

export default Button;

 

728x90