Skip to main content

README

行内样式和类样式

import React, { Component } from "react";

class Box extends Component {
constructor(props) {
super(props);
this.state = {
styleObj: {
fontSize: "50px",
},
};
}
render() {
return (
<div className="container">
{/* 行内样式 */}
<h1 style={{ fontSize: "20px" }}>标题1</h1>
{/* 类样式 */}
<h1 style={this.state.styleObj}>标题2</h1>
</div>
);
}
}
export default Box;

CSS 模块

更新 css 文件名:styles.module.css

.box {
width: 100px;
height: 100px;
border: 1px solid #ccc;
}
import styles from "./styles.module.css";

<div className={styles.box} />;

动态切换样式(classNames)

安装

yarn add classnames -S

使用教程

import React, { Component } from "react";
import ReactDOM from "react-dom";
import classNames from "classnames/bind";
import styles from "./common.css";

let cx = classNames.bind(styles); //建立绑定关系

class Box extends Component {
render() {
let names = cx({
//声明样式对象
success: true,
error: this.props.error, //从标签属性中读取传过来的值
});
return (
<div>
<h1 className={names}>这是提示信息</h1>
</div>
);
}
}

ReactDOM.render(<Box error={false} />, document.getElementById("root"));

CSS-in-JS(styled-components)

安装

yarn add styled-components -S

使用教程

//common.js 样式文件

import React, { Component } from "react";
import ReactDOM from "react-dom";
import { Container } from "./common";
import styled from "styled-components";

const Container = styled.div`
width: 500px;
height: 500px;
background: ${(props) => props.color};
font-size: 30px;
h1 {
font-size: 50px;
}
`;

class Box extends Component {
render() {
return (
<Container color="red">
<h1> hello world</h1>
这里是内容
</Container>
);
}
}

ReactDOM.render(<Box />, document.getElementById("root"));

参考