前言:如果css不实现组件化管理的话,可能会起到冲突,如命名冲突等
目录:
1、下载安装 styled-components
2、全局样式
3、组件内样式
1、下载安装 styled-components
npm install styled-components -D
2、全局样式
- 在 src 下
创建 styled.js
文件,并在 index.js 中引入
- styled.js
import { createGlobalStyle } from 'styled-components'
export const [自定义标签名] = createGlobalStyle`
[全局样式]
`;
- 在你要的组件中引入,并使用标签,这个标签下的都可以适用这个全局样式
import { [自定义标签名] } from '...'
render(){
return (
<[自定义标签名] />
{/*下面的标签都可以适用全局样式*/}
)
}
3、组件内样式
- 创建独立的 styled.js,一般在组件的同层目录下创建,并在组件中引入
styled.js
- 语法:
import styled from 'styled-components'
// attrs 可以添加属性,没有也可以不加
export const [自定义标签的名字] = styled.[标签].attrs({
[属性名]:[属性值]
})`
[普通css代码]
&[这个标签同级的css选择器] —— 如:&.other{}
&::[伪选择器] —— 如:&::after{}
`
- 例子:
import styled from 'styled-components'
import logoimg from '../../static/logo.png' // 引入图片
export const Logo = styled.a.attrs({
href: '/'
})`
width:100px;
height:100px;
background:url(${logoimg});
background-size:contain;
`
- 组件类引用
import React, {Component} from 'react'
import { Logo } from './styled.js'
class Test extends Component{
render(){
return(
<Logo></Logo>
)
}
}
export default Test