首先需要安装style-component 在控住台输入npm install styled-component --save
全局如何使用呢?
在index.js中引入style.js,以下是style.js中的代码(其中使用了reset.css,目的为了在所有浏览器上作统一)
import { createGlobalStyle } from 'styled-components'
export const GlobalStyle=createGlobalStyle `
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
`
如何只针对组件进行使用呢?
首先同样需要在相对应的组件引入import styled from 'styled-components';
然后如果你需要创建一个css组件,那么就可以在style.js中创建并且在需要使用的地方使用
//例如这里我需要创建一个HeaderWapper的组件,在style.js中需要
export const HeaderWapper = styled.div`
background-color: #fff;
border-color: #f0f0f0;
position: relative;
height: 58px;
border-bottom:1px solid #f0f0f0;
`;
//然后在需要使用的组件中引入
import {
HeaderWapper
} from './style';
//最后在需要使用的地方使用
class Header extends Component{
render() {
return (
<HeaderWapper>
</HeaderWapper>
)
}
}
如果需要在组件中单独设置class样式的话可以使用&.class名字来定义:
//首先引入import {
HeaderWapper,
Nav,
NavItem
} from './style';
//然后在需要使用的地方使用,注意这里定义不能直接用class,需要用className
class Header extends Component{
render() {
return (
<HeaderWapper>
<Nav>
<NavItem className='left active'>首页</NavItem>
<NavItem className='left'>下载APP</NavItem>
<NavItem className='right'>登录</NavItem>
<NavItem className='right'>Aa</NavItem>
<NavSearch></NavSearch>
</Nav>
</HeaderWapper>
)
}
}
//在style.js中
export const HeaderWapper = styled.div`
background-color: #fff;
border-color: #f0f0f0;
position: relative;
height: 58px;
border-bottom:1px solid #f0f0f0;
`;
export const Nav = styled.div`
width:960px;
height: 100%;
margin: 0 auto;
padding-right: 70px;
box-sizing:border-box;
`;
export const NavItem = styled.div`
line-height: 56px;
padding: 0 15px;
font-size: 17px;
color:#333;
&.left{
float:left;
}
&.right{
float:right;
color:#969696;
}
&.active {
color:#ea6f5a;
`;
如何修改input的placeholder的值和样式呢?
export const NavSearch = styled.input.attrs({
placeholder: '搜索'
})`
width: 160px;
height:38px;
border:none;
outline:none;
margin-top:9px;
border-radius:19px;
padding: 0 20px;
box-sizing=border-box;
background: #eee;
font-size: 14px;
margin-left:20px;
&::placeholder {
color: #999;
`;