react中使用中使用css的的7中方式中方式(最全总结最全总结)
第一种第一种: 在组件中直接使用在组件中直接使用style
不需要组件从外部引入css文件,直接在组件中书写。
import React, { Component } from "react";
const div1 = {
width: "300px",
margin: "30px auto",
backgroundColor: "#44014C", //驼峰法
minHeight: "200px",
boxSizing: "border-box"
};
class Test extends Component {
constructor(props, context) {
super(props);
}
render() {
return (
<div style={div1}>123</div>
<div style="background-color:red;">
);
}
}
export default Test;
注意事项:
在正常的css中,比如background-color,box-sizing等属性,在style对象div1中的属性中,必须转换成驼峰
法,backgroundColor,boxSizing。而没有连字符的属性,如margin,width等,则在style对象中不变。
在正常的css中,css的值不需要用双引好(“”),如
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
而在react中使用style对象的方式时。值必须用双引号包裹起来。
这种方式的react样式,只作用于当前组件。
第二种第二种: 在组件中引入在组件中引入[name].css文件文件
需要在当前组件开头使用import引入css文件。
import React, { Component } from "react";
import TestChidren from "./TestChidren";
import "@/assets/css/index.scss";
class Test extends Component {
constructor(props, context) {
super(props);
}
render() {
return (
<div>
<div className="link-name">123</div>
<TestChidren>测试子组件的样式</TestChidren>