前置

在 react 中解决组件样式冲突的方案中,如果您喜欢将 css 与 js 分离,可能更习惯于 CSS-Modules;如果习惯了 Vue.js 那样的单文件组件,可能习惯于使用 styled-components 来解决这个问题。使用 CSS-Modules 从老项目迁移过来可能更容易。

安装

npm i styled-components

基本用法

import React from 'react'
import styled from 'styled-components'
import { render } from 'react-dom'
import './index.css' const items = [
{
title: 'title1',
type: 'primary',
desc: 'Lorem ipsum dolor sit amet consectetur '
},
{
title: 'title2',
type: 'other',
desc: 'Lorem ipsum dolor sit amet consectetur ',
},
] function App() {
return (
<div>
{items.map(renderItem)}
</div>
)
} function renderItem(item) {
return (
<Wrap>
<h2>{item.title}</h2>
<p>{item.desc}</p>
</Wrap>
)
} const Wrap = styled.div`
margin: 10px auto 10px;
padding: 10px;
width: 90%;
border-radius: 5px;
background: #eee
` render(<App />, document.getElementById('app'))

实际渲染结果:



我们需要在 JavaScript 模板字符串内部书写 css 样式,为了得到 css 语法高亮,可以使用 vscode 扩展。

嵌套

const Wrap = styled.div`
margin: 10px auto;
padding: 10px;
width: 90%;
border-radius: 5px;
background: #eee; + h2 {
+ color: red
+ }
`

props

function renderItem(item) {
return (
+ <Wrap type={item.type} >
<h2>{item.title}</h2>
<p>{item.desc}</p>
</Wrap>
)
} const Wrap = styled.div`
margin: 10px auto;
padding: 10px;
width: 90%;
border-radius: 5px;
+ background: ${props => props.type === 'primary' ? '#202234' : '#eee'};
`

在模板括号中可使用任意 JavaScript 表达式,这里使用箭头函数,通过 props 接收参数。

继承

使用继承实现上文功能:

import React from 'react'
import styled from 'styled-components'
import { render } from 'react-dom'
import './index.css' const items = [...] function App() {
return (...)
} function renderItem(item) {
+ const Container = item.type === 'primary' ? primaryContainer : OrdinaryContainer
return (
+ <Container>
<h2>{item.title}</h2>
<p>{item.desc}</p>
</Container>
)
} const Wrap = styled.div`
margin: 10px auto 10px;
padding: 10px;
width: 90%;
border-radius: 5px;
- background: ${props => props.type === 'primary' ? '#202234' : '#eee'};
` + const OrdinaryContainer = styled(Wrap)`
+ background: #eee;
+ ` + const primaryContainer = styled(Wrap)`
+ background: #202234;
+ ` render(<App />, document.getElementById('app'))

我们得到同样的效果:

继承的语法

// 如上所示,您应该这样写来实现继承
const OrdinaryContainer = styled(Wrap)``
// 现在已经不支持extend关键字
const OrdinaryContainer = Wrap.extend``

下面给它们共同继承的 Wrap 添加一个border:

const Wrap = styled.div`
margin: 10px auto 10px;
padding: 10px;
width: 90%;
border-radius: 5px;
+ border: 2px solid red;
`

将影响所有继承过 Wrap 的样式变量:

attrs

封装一个文本输入框组件 src/components/Input.jsx

import styled from "styled-components";

const Input = styled.input.attrs({
type: 'text',
padding: props => props.size || "0.5em",
margin: props => props.size || "0.5em"
})`
border: 2px solid #eee;
color: #555;
border-radius: 4px;
margin: ${props=>props.margin};
padding: ${props=>props.padding};
` export default Input

使用

// ..
import Input from './components/Input' function App() {
return (
<div>
<Input></Input>
<Input size="2em"></Input>
</div>
)
} render(<App />, document.getElementById('app'))

createGlobalStyle

在 V4 版本已经将 injectGlobal 移除,使用 createGlobalStyle 代替它设置全局样式,

import React from 'react'
import { render } from 'react-dom'
import styled, {createGlobalStyle} from 'styled-components' // ... function App() {
return (
<div>
<GlobalStyle></GlobalStyle>
{items.map(renderItem)}
</div>
)
} function renderItem(item) {
const Container = item.type === 'primary' ? primaryContainer : OrdinaryContainer
return (
<Container>
<h2>{item.title}</h2>
<p>{item.desc}</p>
</Container>
)
} const GlobalStyle = createGlobalStyle`
*{
margin: 0;
padding: 0;
}
body {
min-height: 100%;
background: #ffb3cc;
}
`
// ... render(<App />, document.getElementById('app'))

ThemeProvider

通过上下文 API 将主题注入组件树中位于其下方任何位置的所有样式组件中。

import React from 'react'
import { render } from 'react-dom'
import styled, {createGlobalStyle, ThemeProvider} from 'styled-components'
import Input from './components/Input' const items = [...] function App() {
return (
<div>
<GlobalStyle></GlobalStyle>
{items.map(renderItem)}
<Input></Input>
<Input size="2em"></Input>
</div>
)
} function renderItem(item) {
const Container = item.type === 'primary' ? primaryContainer : OrdinaryContainer
return (
<Container>
<h2>{item.title}</h2>
<p>{item.desc}</p>
</Container>
)
} // ... const primaryContainer = styled(Wrap)`
background: ${props=>props.theme.primary};
` const theme = {
primary: '#202234'
} render(<ThemeProvider theme={theme}><App /></ThemeProvider>, document.getElementById('app'))

我们需要先导入 ThemeProvider,然后用标签将 <App /> 包裹,需要注意的是必须为 ThemeProvider 标签提供一个 theme 属性,接下来在所有子组件中都可以通过 props.theme.xxx 获取 theme 下的属性。我们将 Input 组件的背景色同样改为 theme 下的 primary

import styled from "styled-components";

const Input = styled.input.attrs({
// ...
})`
// ...
background: ${props=>props.theme.primary};
` export default Input

keyframes

使用 styled-components 时,无法直接在模板字符串中创建 keyframes,需要先导入 styled-components 下的 keframes 对象来创建它。下面看一个简单的实例:

import React from 'react'
import styled, { keyframes } from 'styled-components'
import { render } from 'react-dom' const items = [...] function App() {
return (
<div>
{items.map(renderItem)}
</div>
)
} function renderItem(item) {
const Container = item.type === 'primary' ? primaryContainer : OrdinaryContainer
return (
<Container>
<h2>{item.title}</h2>
<p>{item.desc}</p>
</Container>
)
} // ... const fadeIn = keyframes`
0% {
opacity: 0;
}
100% {
opacity: 1;
}
` const Wrap = styled.div`
// ...
animation: 1.5s ${fadeIn} ease-out;
`
// .. render(<App />, document.getElementById('app'))

到我重新刷新页面,就能看见下面的效果:

react 样式冲突解决方案 styled-components的更多相关文章

  1. styled components草根中文版文档

    1.styled components官网网址 https://www.styled-components.com/docs   以组件的形式来写样式. 1.1安装 yarn add styled-c ...

  2. react className 有多个值时的处理 / react 样式使用 百分比(%) 报错

    1.react className 有多个值时的处理 <fieldset className={`${styles.formFieldset} ${styles.formItem}`}> ...

  3. 百度地图api的覆盖物样式与bootstrap样式冲突解决办法

    使用百度地图api 和 bootstrap ,发现标注样式出现了问题 label左侧 宽度变得非常窄 正常情况下应该是下面这样的: 原因是boostrap样式和百度地图样式冲突了. 解决办法: .ba ...

  4. Atitit 类库冲突解决方案  httpclient-4.5.2.jar

    Atitit 类库冲突解决方案  httpclient-4.5.2.jar 错误提示如下1 版本如下(client and selenium)2 解决流程2 挂载源码 (SSLConnectionSo ...

  5. SVN代码提交冲突解决方案

    SVN代码提交冲突解决方案 1.若你的代码被其他人修改并提交过了,期间你自己也修改过该文件,UPDATE的时候自己代码被覆盖. 右键——>显示日志 查看该文件的更新记录 找到需恢复的版本 右键— ...

  6. SharePoint 2010 中使用Ztree和EasyUI样式冲突问题

    <style type="text/css"> /*解决ztree和SharePoint样式冲突问题*/ .ztree li a { display: inline-b ...

  7. Git冲突解决方案

    Git冲突解决方案 1.  在代码提交时,先更新,若有冲突.先解决冲突.若提交之后在review时才发现无法合并代码时有冲突,需要abandon此次提交的代码. 2.  解决冲突的基本做法,保存本地代 ...

  8. vue2.0 通过v-html指令渲染的富文本无法修改样式的解决方案

    在最近的vue项目中遇到的问题:v-html渲染的富文本,无法在样式表中修改样式: 比如下面的代码,div.descBox里面的p标签的color样式并不是"color: blue" ...

  9. PC端的软件端口和adb 5037端口冲突解决方案

    引用https://www.aliyun.com/jiaocheng/32552.html 阿里云 >  教程中心   >  android教程 >  PC端的软件端口和adb 50 ...

随机推荐

  1. 微信小程序支付、小程序支付功能、小程序支付方法、微信小程序支付方法

    相信大家在做小程序的时候不可避免的会碰到支付功能小程序的支付和pc的是有区别的小程序的支付方法为 wx.requestPayment wx.requestPayment({ timeStamp: '' ...

  2. EF实现简单的增删改查

    1.在项目中添加ADO.NET实体数据模型: 2.接着根据提示配置数据库连接,配置完毕之后项目中生成了大致如下的内容(EF6.x): 其中TestData.tt中的Consumer,Stores是创建 ...

  3. C++中类继承public,protected和private关键字作用详解及派生类的访问权限

    注意:本文有时候会用Visual Studio Code里插件的自动补全功能来展示访问权限的范围(当且仅当自动补全范围等价于对象访问权限范围的时候),但是不代表只要是出现在自动补全范围内的可调用对象/ ...

  4. 关于ES6的let和const

    变量 var存在的问题 可以重复声明 无法限制修改 没有块级作用域 (在全局范围内有效) 存在变量提升 const/let 不可以重复声明 let a = 1; let a = 2; var b = ...

  5. Vuex与axios的封装和调用

    Vuex状态管理 状态就是数据.    在react里有个Flux的数据流管理(单向数据流) 作用1:实现组件之间的数据共享. 作用2:用于缓存.(避免当用户频繁点击,页面不断调接口)     先安装 ...

  6. MSSQL系列 (二):表相关操作、列操作、(唯一、主键、默认、检查、外键、非空)约束、临时表

    1.创建表 --创建学生班级表 create table StuClass ( ClassId int primary key, --班级ID 主键约束 ClassName nvarchar(30) ...

  7. var 的一个坑,以及 let

    选自 Typescript 中文教程. 快速的猜一下下面的代码会返回什么: for (var i = 0; i < 10; i++) { setTimeout(function() { cons ...

  8. C++语法小记---异常处理

    异常处理(C语言) 异常是对代码中可以预知的问题进行处理:代码中不可以预知的问题叫Bug: if () { ... } else { ... } setjmp和longjmp #include < ...

  9. css 过渡样式 transition

    过渡顾名思义就是就是样式改变的一个过程变化 简介 transition: property duration timing-function delay; 值 描述 transition-proper ...

  10. 题解 SP1841 【PPATH - Prime Path】

    模拟赛考到了这个题,但我傻傻的用了\(DFS\),于是爆了零 后来才想明白,因为搜索树的分支很多,但答案的深度却又没有那么深,所以在这里\(BFS\),而\(DFS\)一路搜到底的做法则会稳稳地\(T ...