安装styled-components
npm i styled-components
利用标记的模板文字(JavaScript的最新添加)和CSS的强大功能,样式化组件允许您编写实际的CSS代码来样式化组件。它还删除了组件和样式之间的映射——将组件用作低级样式构造再容易不过了!
- import styled from 'styled-components';
- const Button = styled.button`
- color: grey;
- `;
或者,也可以使用样式对象。这允许从内联样式轻松移植CSS,同时仍然支持更高级的样式组件功能,如组件选择器和媒体查询。
- import styled from 'styled-components';
- const Button = styled.button({
- color: 'grey',
- });
相当于
- import styled from 'styled-components';
- const Button = styled.button`
- color: grey;
- `;
- const LayoutBox = styled.button`
- background: ${props => props.primary ? "#f7f7f7" : "#fff"};
- `;
- render(
- <div>
- <LayoutBox primary >主页面LayoutBox>
- div>
- );
- /** 注意:只能添加原生属性 */
- export const Input = styled.input.attrs({
- type: 'text',
- length:10
- })`
- background: palevioletred;
- border-radius: 3px;
- border: none;
- color: white;
- //样式组件(Input)传过来的属性对象
- padding: ${(props) => props.padding}
- `;
-
- export const PasswordInput = styled(Input).attrs({
- type: 'password',
- })`
- background: #8a8a8a;
- length: 300px
- `
- /**
- * 也可以引入第三方样式(如第三方的small属性)
- */
- <Button className="small">
- Styled Components
- Button>
-
- const Button = styled.button.attrs({
- className: 'small',
- })`
- background: black;
- color: white;
- cursor: pointer;
- margin: 1em;
- padding: 0.25em 1em;
- border: 2px solid black;
- border-radius: 3px;
- `;
-
-
- import styled from 'styled-components';
-
- const BaseButton = styled.button`
- color: white;
- background-color: blue;
- padding: 10px 20px;
- `;
-
- //传入了BaseButton的样式然后覆盖
- const SpecificButton = styled(BaseButton)`
- background-color: red; /* 覆盖基础组件的背景颜色 */
- `;
-
- // 使用
- <BaseButton>我是基础按钮BaseButton>
- <SpecificButton>我是有特殊样式的按钮SpecificButton>