jineecode

styled-components 이중 extends 해주기 본문

CSS/css in js

styled-components 이중 extends 해주기

지니코딩 2022. 2. 24. 16:37

react-native 기준입니다.

 

 

기본적인 extends

잘 만들어진 styled-component를 괄호를 사용하여 extends 해준다.

// The Button from the last section without the interpolations
const Button = styled.button`
  color: palevioletred;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`;

// A new component based on Button, but with some override styles
const TomatoButton = styled(Button)`
  color: tomato;
  border-color: tomato;
`;

render(
  <div>
    <Button>Normal Button</Button>
    <TomatoButton>Tomato Button</TomatoButton>
  </div>
);

 

같은 문제를 앓고 있던 스택오버플로우

더보기

https://stackoverflow.com/questions/50524030/how-do-i-extent-multiple-components-styles-in-styled-components

 

How do I extent multiple components' styles in styled-components

I have these Components:... const Card = () => <span>There is content</span> const CardItem = styled(Card)` background-color: red; ` Now I want another component from the above ...

stackoverflow.com

 

const Card = () => <span>There is content</span>

const CardItem = styled(Card)`
  background-color: red;
`

 

const Card2 = styled(CardItem)`
  background-color: green;
`

 

이런 식으로 하면 background-color 가 바뀌지 않는다. 

리액트 네이티브에서는 className이 없으므로 다른 방법을 찾아야만 했다.

 

컴포넌트를 태운 뒤 extends 하는 법

1. Input 의 Props에 ...props을 태운다

const Input: React.FC<IProps> = ({
  ...props
}) => {
  return (
   <>
      <InputField {...props} />
  </> 
  );
};

const InputField = styled.TextInput`
  width: 100%;
`;

 

2. 위에서 만든 컴포넌트 Input을 사용한 또다른 컴포넌트 (InputPhone)에도 계속 props를 태워준다 

import Input from '~/components/atoms/Input';

const InputPhone = ({...props}) => {
  return (
    <>
      <Input {...props}/>
    </>
  );
};

export default InputPhone;

 

3. InputPhone의 스타일을 수정하는 법

import InputPhone from '~/components/atoms/Input/InputPhone';

const Certification = () => {

  return (
    <>
        <InputPhoneWrapper />
    </>
  );
};

export default Certification;


const InputPhoneWrapper = styled(InputPhone)`
  width: ${Theme.width(236)}px;
`;

이렇게 하면 계속 props를 타고 내려오기 때문에 extends가 가능하다.

 

Comments