react的样式处理方案及样式透穿(styled-components)

方案一:css in js 

安装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>

  • 10
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值