본문 바로가기

TS

(TS) 부모와 자식 컴포넌트 / styled-component props 전달

부모 컴포넌트 Header.tsx

<RequestConsultingButton inverted={inverted}>
  상담 신청하기
</RequestConsultingButton>

 

자식 컴포넌트 RequestConsultringButton.tsx

interface invertedProps {
  inverted: boolean
}

const RequestConsultingButton = ({
  props,
  children,
}: {
  props: invertedProps
  children: string
}) => {
  return (
    <Container inverted={props.inverted}>
      <p className="text">{children}</p>
    </Container>
  )
}

일반적인 방법으로 코드 작성.

interface (혹은 타입 지정)  지정하여 처리

 

부모 컴포넌트에서 IntrinsicAttributes 오류 발생

오류 발생 원인을 정확하게 모르겠다. 이리 저리 찾아 봤으나 이유는 모르나 

다른 형태로 코드를 작성하여서 해결하였다.

 

 

새롭게 작성된

자식 컴포넌트 RequestConsultringButton.tsx

따로 인터페이스나 타입 지정을 하지 않고

매개변수에 타입을 지정하였다.

const RequestConsultingButton: React.FC<{
  inverted: boolean
  children: string
}> = ({ inverted, children }) => {
  return (
    <Container inverted={inverted}>
      <p className="text">{children}</p>
    </Container>
  )
}

export default RequestConsultingButton

const Container = styled.button<{ inverted: boolean }>`
  margin-right: 24px;
  color: ${props => (props.inverted ? 'var(--primaryBlue)' : 'white')};
  border: ${props =>
    props.inverted ? '1px solid var(--primaryBlue)' : '1px solid white'};

  .text {
    font-size: 14px;
  }
`

 

TS에서 props 전달시 전달되는 props가 다수일 경우

자식 컴포넌트에서 props의 type을 지정하고 객체의 속성으로 접근하는 방법을 알고 있었는데

그 방식이 현재 위의 사례에서는 올바르게 적용되지 않고 있었다.