본문 바로가기

html&css

[styled-components] Attaching additional props

 

 

  attrs는 컴포넌트에 추가 porps를 더 할 수 있는 styled-components의 메소드이다. 이러한 props는 styled-components가 렌더링하는 기본 DOM 노드 또는 컴포넌트에 적용된다. 

  attrs 메소드는 객체를 파라미터로 사용하여 객체의 각 키-값이 컴포넌트에 연결되어야 하는 props를 나타낸다. 값은 정적 값이거나 컴포넌트에 전달된 props를 기반으로 하는 동적 값일 수도 있다.

const Button = styled.button.attrs(props => ({
  type: props.submit ? 'submit' : 'button'
}))`
  background-color: ${props => props.primary ? 'blue' : 'white'};
  color: ${props => props.primary ? 'white' : 'black'};
`

여기서 attrs개체가 type props를 Button 컴포넌트의 기본 버튼 엘리먼트에 연결시켜 준다. submit props가 true이면 submit으로 그렇지 않으면 button으로 타입이 지정된다. 이런 방식으로 attrs를 사용하면 컴포넌트 계층 구조의 모든 레벨에 각각 전달하지 않더라도 추가적으로 props를 쉽게 컴포넌트에 연결할 수 있다.

 

  attrs를 재정의할 수도 있다. 이미 attrs를 통해 컴포넌트에 추가 props가 더해진 컴포넌트의 경우에 상속을 통해서 재정의 할 수 있다.

const Input = styled.input.attrs(props => ({
  type: 'text';
  size: props.size || '1em';
}))`
  border: 2px solid palevioletred;
  margin: ${props => props.size};
  padding: ${props => props.size};
`;

const PasswordInput = styled(Input).attrs({
  type: 'password';
})`
  border: 2px solid aqua;
`;

이렇게 하면 기존 Input은 text 타입으로 상속받은 PasswordInput은 password 타입으로 사용할 수 있다.