组件中DOM样式
第一种、行内样式
通过使用表达式传入样式对象来实现:
方式一:
<div style={{ color: "red", fontSize: 30 + "px" }}>
通过行内样式进行设置
</div>
需要注意的是{{}}
,此处有两对花括号。第一个表示我们在要JSX里插入JS了,第二个是对象的括号
方式二:
constructor(props) {
super(props);
this.state = {
style: true,
style1: {
color: "blue",
fontSize: "30px"
},
style2: {
color: "red",
fontSize: "15px"
}
};
}
render() {
return <div style={this.state.style1}>通过行内样式进行设置</div>;
}
此种方式,是在构造函数的state
里进行样式的编写,在标签内部进行调用。
第二种、外部引用 [name].css文件
React推荐我们使用行内样式,因为React觉得每一个组件都是一个独立的整体。
其实我们大多数情况下还是大量的在为元素添加类名,但是需要注意的是,class需要写成className(因为毕竟是在写类js代码,会收到js规则的限制,而class是关键字
style.css
.a {
color: yellow;
font-size: 30px;
}
正常写css文件,然后引入
import "./views/index/style.css";
render() {
return <div className="a">通过引入外部css文件进行设置</div>;
}
第三种、引入[name].scss文件
引入react内部已经支持了后缀为scss的文件,所以只需要安装node-sass
即可,因为有node-sass,scss文件才能在node环境上编译成css文件。
安装 node-sass
yarn add node-sass
然后编写scss文件
//index.scss
.App{
background-color: #282c34;
.header{
min-height: 100vh;
color: white;
}
}
关于如何详细的使用sass,请查看 sass官网
这种方式引入的css样式,同样会作用于当前组件及其所有后代组件。
第四种、 使用styled-components
首先需要安装 styled-components
yarn add styled-components
然后创建一个js文件 (注意是js文件,不是css文件)
import styled from "styled-components";
export const Style1 = styled.div`
height: 50px;
color: red;
fontsize: 30px;
`;
export const Style2 = styled.div`
height: 50px;
color: blue;
fontsize: 30px;
`;
组件中使用styled-components样式
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { Style1, Style2 } from "./style";
class Index extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div>
<Style1>通过styled-components</Style1>
<Style2>通过styled-components</Style2>
</div>
);
}
}
ReactDOM.render(<Index name="react" />, document.getElementById("root"));
这种方式是将整个css样式,和html节点整体合并成一个组件。引入这个组件html和css都有了。它的好处在于可以随时通过往组件上传入 属性,来动态的改变样式。对于处理变量、媒体查询、伪类等较方便的。
这种方式的css也只对当前组件有效。具体用法,请查看 styled-components官网。