Skip to main content

Class & Style

一、Class

与传统的标签 class 不同,React需要使用 className 来识别

<div className="item active"></div>

1、动态添加

<div className={`item ${this.state.active ? 'active' : ''}`}></div>

<div className={['item', (this.state.active ? 'active' : '')].join(' ')}></div>
PS

className 可以自由组装,但结果必须是一个字符串

Live Editor
Result
Loading...

2、模块化(modules)

webpack CSS Modules 配置

module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: true,
},
},
],
},
}

home.jsx

import styles from './home.module.scss'

function home() {
return (
<div className={styles.home}>
<h1 className={styles.title}></h1>
</div>
)
}

home.module.scss

.home {
padding: 20px;
.title {
font-size: 24px;
}
}

3、class 组合

需要安装 classnames 依赖

> npm install classnames -S

使用

import classnames from 'classnames'

function Example() {
return <div className={classnames('box', 'box-blue')}></div>
}

import classnames from 'classnames'
import styles from './home.module.scss'

function Example() {
return <div className={classnames('box', 'box-blue', styles.home)}></div>
}

4、模块化 + 全局

PS

使用这种方式主要是想避开太多的 styles.xxx ,只使用一个大的作用域限制,然后正常写样式会顺心很多。

import styles from './home.module.scss'
import Header from '../components/Header'

function Example() {
return (
<div className={styles.home}>
<Header/>
</div>
)
}

home.module.scss

.home {
display: flex;
:global {
@import "scss/Header.scss";
// @import "scss/Footer.scss"; // 可以多个导入
}
}

Header.scss

.header {
height: 60px;
.title {
font-size: 22px;
}
}

Header.js

class Header extends React.Component {
constructor(props) {
super(props)
}

render() {
return (
<div className="header">
<h1 className="title">标题</h1>
</div>
)
}
}

export default Header

二、Style

React是通过 {} JSON对象处理内置 style 样式的,采用驼峰命名法,px 单位可省略。

<div style={{color: '#f00', marginLeft: 20, height: 100}}>
Hello World!
</div>
Live Editor
Result
Loading...

1、动态添加

<div style={{display: (this.state.hidden ? "none" : "block"), "color":"red"}}></div>
Live Editor
Result
Loading...

2、样式化组件(styled-components)

需要安装 styled-components 依赖

> npm install styled-components -S

使用

import styled from 'styled-components'

const Logo = styled.div`
.logo {
padding: 0 20px;
height: 60px;
}
.logo h1 {
font-size: 24px;
line-height: 60px;
}
`

function Logo() {
return (
<Logo>
<h1>Hello World</h1>
</Logo>
)
}

3、样式穿透

:globalCSS Modules 提出的概念,主要是用来修改全局样式

全局作用域

:global {
.ant-input {
margin-bottom: 0 !important;
}
}

块级作用域

.search {
.left {
flex: 1;
}
:global {
.ant-input {
margin-bottom: 0 !important;
}
}
}

指定class

:global(.ant-form-item-control-input-content) {
position: relative;
}