일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- for in
- 기초
- 함수선언식
- for of
- properties
- ELSE
- flex
- 논리연산자
- 문자열
- 변수
- if else
- justify-content
- flex-wrap
- javascript
- 함수표현식
- 반복문
- boolean
- frontend
- 속성
- flex-direction
- align-content
- 프론트엔드
- 조건문
- for
- 비교연산자
- 함수
- 타입
- 화살표함수
- typeof
- Methods
- Today
- Total
하얀 코딩
[Styled Component - 3] attrs 본문
styled-components의 attrs 함수를 사용하면 스타일 컴포넌트에 속성(attribute)을 추가할 수 있습니다.
이를 통해 스타일 컴포넌트에 동적인 속성을 전달하고, 해당 속성에 기반한 스타일을 정의할 수 있습니다.
attrs 함수는 첫 번째 매개변수로 속성을 포함한 객체를 받습니다.
각 속성은 이름과 값을 가지며, 해당 속성을 스타일 컴포넌트에 전달할 때 사용됩니다.
import styled from 'styled-components';
const Input = styled.input.attrs(
{
type: 'text',
placeholder: "Enter text"
}
)`
padding: 10px;
border: 1px solid #ccc;
`;
const App = () => {
return <Input />;
};
위의 예시에서 Input 스타일 컴포넌트는 input 요소를 스타일링하는 데 사용됩니다.
attrs 함수를 사용하여 type과 placeholder 속성을 정의했습니다.
이렇게 하면 Input 컴포넌트에는 기본적으로 type="text"와 placeholder="Enter text" 속성이 적용됩니다.
또한, attrs 함수는 함수를 인수로 받아 동적인 속성을 정의할 수도 있습니다.
함수를 사용하면 컴포넌트의 속성이나 상태에 따라 동적으로 속성 값을 생성할 수 있습니다.
import styled from 'styled-components';
const Button = styled.button.attrs(props => ({
disabled: props.disabled ? true : undefined,
}))`
/* 스타일 정의 */
`;
const App = () => {
const isDisabled = true;
return <Button disabled={isDisabled}>Submit</Button>;
};
위의 예시에서 Button 컴포넌트는 disabled 속성을 동적으로 처리합니다.
attrs 함수를 사용하여 disabled 속성을 정의하고, props.disabled 값을 확인하여 true로 설정되면
disabled 속성을 true로 지정합니다. 이를 통해 버튼이 비활성화 상태인 경우 disabled 속성이 적용됩니다.
styled-components의 attrs 함수를 사용하면 스타일 컴포넌트에 동적인 속성을 추가하고,
해당 속성에 기반한 스타일을 쉽게 정의할 수 있습니다.
'Styled Components' 카테고리의 다른 글
[Styled Component - 7] & (1) | 2023.06.05 |
---|---|
[Styled Component - 6] ThemeProvider (0) | 2023.06.05 |
[Styled Component - 5] keyframes (0) | 2023.06.05 |
[Styled Component - 2] Props 활용하기 (0) | 2023.06.02 |
[Styled Component - 1] 기본 사용법 (0) | 2023.06.02 |