使用styled-components第三方模块来解决,并且styled-components还可以将标签和样式写到一起,作为一个有样式的组件,这样样式就是这个组件的私有样式,不会给其他组件造成影响,也很方便。
import {createGlobalStyle} from 'styled-components';
export const GlobalStyled = 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 React from 'react';
import {GlobalStyled} from './style.js';
import Header from './common/header'
function App() {
return (
<div className="App">
<GlobalStyled/>
<Header/>
</div>
);
}
export default App;
import styled from 'styled-components'
import logoPic from '../../statics/jianshulogo.png'
export const HeaderWrapper = styled.div`
position: relative;
height: 56px;
border-bottom: 1px solid #f0f0f0;
`
export const Logo = styled.a`
position: absolute;
top: 0;
left: 0;
display: block;
width: 100px;
height: 56px;
background: url(${logoPic});
background-size: contain;
`
有样式的组件,哪里需要放哪里就行了,styled-components构造出来的组件,一般react标签有的属性,组件都有, 不过react标签中ref属性,在styled组件中是用innerRef。
import React,{Component} from "react"
import {HeaderWrapper,Logo} from "./style"
class Header extends Component {
render(){
return (
<HeaderWrapper>
<Logo href="/"></Logo>
</HeaderWrapper>
)
}
}
export default Header
export const Logo = styled.a.attr({
href: '/'
})`
position: absolute;
top: 0;
left: 0;
display: block;
width: 100px;
height: 56px;
background: url(${logoPic});
background-size: contain;
`
再注意一个问题,之前学习配置webpack的时候,我们知道.css,.less,sacs等样式文件,webpack配置后是可以将其解析的,像background:url(),根据路径webpack会打包图片也是没有问题的,但是这里用styled-components,是不会解析background:url(),不会解析路径,获取图片的,而只是当成一个路径字符串,返回到网页中去
import styled from 'styled-components' import logoPic from '../../statics/jianshulogo.png'
export const HeaderWrapper = styled.div`
position: relative;
height: 56px;
border-bottom: 1px solid #f0f0f0;
`
export const Logo = styled.a`
position: absolute;
top: 0;
left: 0;
display: block;
width: 100px;
height: 56px;
background: red url(${logoPic})
`