ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [React] styled-components interface, optional props, Type State (typescripts)
    IT/React 2022. 6. 9. 19:10
    기본 설명
    // 1
    const x = (a: number, b: number) => a + b;
    
    // 2
    interface Sum{
    	a: number;
    	b: number;
    }
    • 1 번 처럼 선언을 할때 number 타입을 지정해줄 수 있는 방법과
    • interface 라는 것을 사용하여 a,b 타입을 number로 지정해줄 수 있는것 

     

    styled-components 응용
    • styled-components의 props를 typeScripts 로 타입을 정해주고 엄격한 언어 방식으로 변경 가능하다

     

    import Circle from './Circle';
    
    function App() {
      return (
        <div>
          <Circle bgColor="teal" />
          <Circle bgColor="tomato" />
        </div>
      );
    }
    
    export default App;
    • App.tsx 파일에서
    • Circle 컴포넌트를 호출하면서 bgColor="teal" 입력하여 props를 전달해준다.

     

    interface CircleProps {
    	bgColor: string;
    }
    
    interface ContainerProps {
    	bgColor: string;
    }
    
    const Container = styled.div<ContainerProps>`
    	width: 200px;
    	height: 200px;
    	background-color: ${props => props.bgColor};
    	border-radius: 100px;
    `
    
    function Circle({ bgColor }: CircleProps) {
    	return <Container bgColor={bgColor} />
    
    }
    • props와 styled-components를 타입을 강제해주고 코드를 실행 하기 전 타입과 존재 여부를 검사하여
    • 코드 후 에러를 사전에 잡아 낼 수 있다는 장점이 있다.

     

     

    Optional props 설명
    • default 값을 설정하고 해당 props를 사용하지 않아도 되는 Option을 생성하는 것

     

    interface CircleProps {
    	bgColor: string;
    	// 반드시 넣어줘야하는 require 하지만 옵션으로 넣어주고 싶다.
    	borderColor?: string;
    	// ? 를 넣으면 없을 수도 있다라는 것
    	// string or undefine
    	text?: string;
    }
    
    function Circle({ bgColor, borderColor, text = "default" }: CircleProps) {
    	return <Container bgColor={bgColor} borderColor={borderColor ?? bgColor} />
    }
    
    export default Circle;
    • props의 이름 뒤에 ? 를 붙인다면 string | undefined 라는 뜻
    • Circle() 함수 안에 default 값을 입력할 수 있고
    • 컴포넌트 부분에서 default 값을 입력해 줄 수 있다.
    State Type

    typescripts React를 사용하기 때문에 state를 사용할때에도 타입을 맞추어야한다.

    const [value, setValue] = useState(1);
    
    setValue(2)
    // 가능
    
    setValue("hi")
    // 불가능
    • 기본적인 형태는 위와 같은 형태를 이루게 된다.
    • 물론 일반 React를 사용할때에도 State의 타입을 바꾸는 경우는 흔치 않을 것이지만
    • js 에서는 해당 코드가 실행 된 후 에러를 발생 시키는 것을 차이점으로 보고있다.

     

    • 만약 state의 타입 변경을 허용하고싶다면
    const [value, setValue] = useState<number | string>(1);
    
    setValue(2);
    // 허용
    
    setValue("Hello");
    // 허용
    
    const [array, setArray] = useState< array | null >();
    // 해당 방식으로 초기값을 지정하지 않을 수 있고 배열에 사용하면 좋을 것
    • 해당 방식이 있다
Designed by Tistory.