react中使用css的7中方式(最全总结)
第一种:在组件中直接使用style
不需要组件从外部引入css文件,直接在组件中书写。
importReact,{Component}from"react";
constdiv1={
width:"300px",
margin:"30pxauto",
backgroundColor:"#44014C",//驼峰法
minHeight:"200px",
boxSizing:"border-box"
};
classTestextendsComponent{
constructor(props,context){
super(props);
}
render(){
return(
123 注意事项:
- 在正常的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文件。
importReact,{Component}from"react";
importTestChidrenfrom"./TestChidren";
import"@/assets/css/index.scss";
classTestextendsComponent{
constructor(props,context){
super(props);
}
render(){
return(
123
测试子组件的样式
这种方式引入的css样式,会作用于当前组件及其所有后代组件。
第三种:3、在组件中引入[name].scss文件
引入react内部已经支持了后缀为scss的文件,所以只需要安装node-sass即可,因为有个node-sass,scss文件才能在node环境上编译成css文件。
>yarnaddnode-sass
然后编写scss文件
//index.scss
.App{
background-color:#282c34;
.header{
min-height:100vh;
color:white;
}
}
关于如何详细的使用sass,请查看sass官网
这种方式引入的css样式,同样会作用于当前组件及其所有后代组件。
第四种:在组件中引入[name].module.css文件
将css文件作为一个模块引入,这个模块中的所有css,只作用于当前组件。不会影响当前组件的后代组件。
importReact,{Component}from"react";
importTestChildfrom"./TestChild";
importmoduleCssfrom"./test.module.css";
classTestextendsComponent{
constructor(props,context){
super(props);
}
render(){
return(
321321