React | Styled Components(2)
8005 단어 styled componentsReactReact
Styled-Components
<설치>
npm install --save styled-components
Getting Started (styled-component 정의)
// styled-components 라이브러리에서 import 해온 styled라는 객체를 이용합니다
// 아래와 같이 h1 태그를 만들어 Title이라는 스타일드 컴포넌트를 만들 수 있습니다
import styled from 'styled-components'
render(
<Wrapper>
<Title>
Hello World!
</Title>
</Wrapper>
);
// html 태그 이름 뒤 Tagged Templete 문법을 활용해 CSS 속성을 정의하고 있습니다
// 앞서 학습했던 Templete Literals 문법(``)의 확장이라고 생각해도 좋습니다 (링크)
const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`;
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
Adapting based on props (가장 기본적이고 많이 쓰이는 항목)
render(
<div>
<Button>Normal</Button>
<Button width="100">Primary</Button>
</div>
);
// 만약 Button 컴포넌트에 전달된 props(width)가 200 미만(조건)이면
// 삼항연산자 true : "palevioletred"
// 삼항연산자 false : "white"
const Button = styled.button`
background: ${props => props.width < 200 ? "palevioletred" : "white"};
color: ${props => props.primary ? "white" : "palevioletred"};
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`;
Extending Styles
render(
<div>
<Button>Normal Button</Button>
<TomatoAnchorButton>Tomato Button</TomatoAnchorButton>
</div>
);
// The Button from the last section without the interpolations
const Button = styled.div`
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
// Button의 속성을 상속 받아 새로운 anchor 태그를 생성
const TomatoAnchorButton = styled(Button.withComponent("a"))`
color: tomato;
border-color: tomato;
`;
Nesting
render(
<>
<Thing>Hello world!</Thing>
<Thing>How ya doing?</Thing>
<Thing className="something">
<span className="contents">The sun is shining...<span>
</Thing>
<div>Pretty nice day today.</div>
<Thing>Don't you think?</Thing>
<div className="something-else">
<Thing>Splendid.</Thing>
</div>
</>
)
const Thing = styled.div`
color: blue;
&:hover {
color: red;
}
#id {
div {
background: orange;
}
}
.something-else & {
border: 1px solid;
}
`
Author And Source
이 문제에 관하여(React | Styled Components(2)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@dudrbs1040/React-Styled-Components2저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)