styled-components 是一个给 React 量身定制的一个库,奉行 React 中 all in js 的设计理念,并发挥到极致,让 CSS 也能称为一个个 JS 模块。
使用 styled-components 解决了哪些痛点?
export const SearchWrapper = styled.div`
position: relative;
float: left;
.zoom {
right: 5px;
&.focused {
background: #777;
color: #fff;
}
}
`;
<RecommendItem imgUrl={'xxx'}/>
export const RecommendItem = styled.div`
width: 280px;
height: 50px;
background: url(${(props) => props.imgUrl});
background-size: contain;
`
// index.jsx
<HeaderWrapper>
<Logo/>
<Nav>
<NavItem className='left active'>首页</NavItem>
<NavItem className='left'>下载App</NavItem>
<NavItem className='right'>
<i className="iconfont"></i>
</NavItem>
<SearchWrapper>
<NavSearch></NavSearch>
<i className='iconfont'></i>
</SearchWrapper>
</Nav>
<Addition>
<Button className='writting'>
<i className="iconfont"></i>
来参加
</Button>
<Button className='reg'>注册</Button>
</Addition>
</HeaderWrapper>
//index.js
import styled from 'styled-components';
export const HeaderWrapper = styled.div`
z-index: 1;
position: relative;
height: 56px;
border-bottom: 1px solid #f0f0f0;
`;
export const Logo = styled.div`
position: absolute;
top: 0;
left: 0;
display: block;
width: 100px;
height: 56px;
background: url(${logoPic});
background-size: contain;
`;
export const Nav = styled.div`
width: 960px;
height: 100%;
padding-right: 70px;
box-sizing: border-box;
margin: 0 auto;
`;
//......
//iconfont.js
//全局样式同理
import {createGlobalStyle} from 'styled-components'
export const IconStyle = createGlobalStyle`
@font-face {
font-family: "iconfont";
src: url('./iconfont.eot?t=1561883078042'); /* IE9 */
src: url('./iconfont.eot?t=1561883078042#iefix') format('embedded-opentype'), /* IE6-IE8
//...
}
.iconfont {
font-family: "iconfont" !important;
font-size: 16px;
font-style: normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
`
import { IconStyle } from './statics/iconfont/iconfont'
import { GlobalStyle } from './style'
//import ...
function App() {
return (
<Provider store={store}>
<div>
{/* 通过标签形式引入这些样式 */}
<GlobalStyle></GlobalStyle>
<IconStyle></IconStyle>
<Header />
<BrowserRouter>
<div>
<Route path='/' exact component={Home}></Route>
<Route path='/detail' exact component={Detail}></Route>
</div>
</BrowserRouter>
</div>
</Provider>
);
}
export default App;