首页 > 语言 > JavaScript > 正文

react中使用css的7中方式(最全总结)

2024-05-06 15:42:36
字体:
来源:转载
供稿:网友

第一种: 在组件中直接使用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>   </div>  ); }}export default Test;

这种方式引入的css样式,会作用于当前组件及其所有后代组件。

第三种: 3、在组件中引入[name].scss文件

引入react内部已经支持了后缀为scss的文件,所以只需要安装node-sass即可,因为有个node-sass,scss文件才能在node环境上编译成css文件。

>yarn add node-sass

然后编写scss文件

//index.scss.App{ background-color: #282c34; .header{  min-height: 100vh;  color: white; }}

关于如何详细的使用sass,请查看sass官网

这种方式引入的css样式,同样会作用于当前组件及其所有后代组件。

第四种: 在组件中引入[name].module.css文件

将css文件作为一个模块引入,这个模块中的所有css,只作用于当前组件。不会影响当前组件的后代组件。

import React, { Component } from "react";import TestChild from "./TestChild";import moduleCss from "./test.module.css";class Test extends Component { constructor(props, context) {  super(props); }   render() {  return (   <div>    <div className={moduleCss.linkName}>321321</div>    <TestChild></TestChild>   </div>  ); }}export default Test;            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选