React中使用CSS
第一种: 在组件中直接使用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> <div style={div1}>123</div> <div style="background-color:red;"> </div> ); } } export default Test; 注意事项: 在正常的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对象的方式时。值必须用双引号包裹起来。 第二种: 在组件中引入[name].css文件需要在当前组件开头使用import引入css文件。 import React,{ Component } from "react"; import TestChidren from "./TestChidren"; import "@/assets/css/index.css"; 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样式,会作用于当前组件及其所有后代组件。 第三种: 在组件中引入[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官网 第四种: 在组件中引入[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; 这种方式可以看做是前面第一种在组件中使用style的升级版。完全将css和组件分离开,又不会影响其他组件。 第五种: 在组件中引入 [name].module.scss文件类似于第四种,区别是第四种引入css module,而这种是引入 scss module而已。 import React,{ Component } from "react"; import TestChild from "./TestChild"; import moduleCss from "./test.module.scss"; class Test extends Component { constructor(props,sans-serif; font-size: 16px'>同样这种方式可以看做是前面第一种在组件中使用style的升级版。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |