项目源码
github.com/astak16/act…
项目结构
src/common; // 公共组件
src/pages; // 页面
src/static; // 静态资源
src/store; // 主 store
App.js; // 根组件
index.css; // 样式
index.js; // 入口文件
重置 css
搜索reset.css,复制过来
styled-components
css文件一旦在一个文件中被引入,会在全局中生效
这样写css会有些问题,当页面中有多个组件时,样式存在被覆盖的风险
我们希望在写样式的时候,每个组件的样式是独立的,不会互相的影响
使用
将index.css重命名为style.js
在index.js引入style.js
import "style.js";
style.js
import { injectGlobal } from "styled-components";
injectGlobal`
body{
padding: 10px
}
`;
在组件中使用
组件声明
// Header/style.js
import styled from "styled-components";
export const HeaderWrapper = styled.div`
height: 56px;
`;
// Header/index.js
import { HeaderWrapper } from "./style";
class Header extends Component{
render() {
return ;
}
}
图片使用
在style.js中使用背景图片的话,直接使用background: url('/images/logo.png')是没有效果的,因为webpack在打包的时候,不知道工程目录是啥样的,它会把路径当成字符串
需要这样写
import logoPic from "/images/logo.png";
export const Logo = style.a`
background: url(${logoPic})
`;
设置属性
import logoPic from "/images/logo.png";
export const Logo = style.a.attr({
href: "/",
})`
background: url(${logoPic})
`;
参数传递
组件中要传递不同的参数进来,styled提供了函数功能
1
1
//