React实战——css组件化

前言:如果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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值