React-样式使用

​🌈个人主页:前端青山

🔥系列专栏:React篇

🔖人终将被年少不可得之物困其一生

依旧青山,本期给大家带来React篇专栏内容:React-样式使用

目录

1、行内样式

2、使用className属性

[3、css module模块化](#3、css module模块化)

4、styled-components

5、scss的使用

6、less的使用

[内联样式(Inline Styles)](#内联样式(Inline Styles))

项目中会经常使用css样式来修饰页面效果

也可以结合css预编译器进行使用

css预编译器(变量、嵌套、混入、函数) 最终要编译为css

常用css预编译器:

sass、scss是一种 scss是sass的第三个版本 编译器发生了改变 node-sass dart-sass

less

stylus

1、行内样式

使用标签的style属性,JSX语法中style属性的值的为对象结构,css属性的名称为大驼峰,如果值为非数字则使用引号包裹

javascript 复制代码
import React, { Component } from 'react'
​
export default class App extends Component {
  render() {
    return (
      // style行内样式
      <div
        style={{
          border: '1px solid #ccc',
          width: '25%',
          marginTop: 10,
          marginLeft: 10,
          display: 'flex',
          flexDirection:'column',
          alignItems:'center'
        }}
      >
        <div>名称:皮卡丘</div>
        <div>技能:十万伏特</div>
        <div>体态:黄色</div>
      </div>
    )
  }
}
复制代码

2、使用className属性

可以将样式进行抽离出来,并且可以进行复用。但是会存在样式污染的情况,也就是选择器名称不能够重名。

javascript 复制代码
.card {
  border: 1px solid #ccc;
  width: 25%;
  margin-top: 10px;
  margin-left: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
​
import React, { Component } from 'react'
import './assets/styles/App.module.css'
export default class App extends Component {
  render() {
    return (
      <div>
        <div className="card">
          <div>名称:皮卡丘</div>
          <div>技能:十万伏特</div>
          <div>体态:黄色</div>
        </div>
        <Child></Child>
      </div>
    )
  }
}
复制代码

3、css module模块化

底层脚手架(webpack)在加载样式文件时,通过module模块化,编译后,把css选择器相同的生成一个唯一的名称,这样就可以避免由于选择名称相同,导致样式的覆盖和污染了。

vue中 <style scoped></style>

src\assets\styles\Child.module.css

javascript 复制代码
.card {
  border: 1px solid red;
  width: 25%;
  margin-top: 10px;
  margin-left: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
​

src\assets\styles\App.module.css

javascript 复制代码
.card {
  border: 1px solid red;
  width: 25%;
  margin-top: 10px;
  margin-left: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
复制代码

src\Child.jsx

javascript 复制代码
import React, { Component } from 'react'
//module模块化css后  实际文件会当做一个对象加载进来
import styles from './assets/styles/Child.module.css'
export default class Child extends Component {
  render() {
    return <div className={styles.card}>Child</div>
  }
}
​

src\App.js

javascript 复制代码
import React, { Component } from 'react'
import styles from './assets/styles/App.module.css'
import Child from './Child'
export default class App extends Component {
  render() {
    return (
      <div>
        {/* // style行内样式 */}
        <div className={styles.card}>
          <div>名称:皮卡丘</div>
          <div>技能:十万伏特</div>
          <div>体态:黄色</div>
        </div>
        <Child></Child>
      </div>
    )
  }
}
复制代码

4、styled-components

在react中为了能够使样式进行动态变化,需要在js中完成css的设置。css-in-js技术,在react社区中有多种样式编写的方案。

styled-components是其中优秀方案之一,将样式同时编写在组件的jsx文件中,以达到编写和管理方便的情况。

继承、变量等写法

安装

javascript 复制代码
npm i styled-components

src\App.js

javascript 复制代码
import React, { Component } from 'react'
import Child from './Child'
// 1、引入styled-components 样式库
import styled from 'styled-components'
// 2、创建一个组件容器 并编写样式
const Card = styled.div`
  border: 1px solid #ccc;
  width: 25%;
  margin-top: 10px;
  margin-left: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
`
export default class App extends Component {
  render() {
    return (
      <div>
        {/* 3、将编写好的组件样式 进行套用 和组件标签的使用方式基本一致 */}
        <Card>
          <div>名称:皮卡丘</div>
          <div>技能:十万伏特</div>
          <div>体态:黄色</div>
        </Card>
        <Child></Child>
      </div>
    )
  }
}
复制代码

样式继承和属性传递

javascript 复制代码
import React, { Component } from 'react'
import styled from 'styled-components'
const Title = styled.div`
  width: 200px;
  height: 100px;
  border: 1px solid black;
`
// 样式继承  将原有的样式进行复用  没有设置的复用  有设置的的以自身为准
const Title1 = styled(Title)`
  height: 50px;
  color: red;
`
// 属性传递  变量使用
const Color = styled.div`
  color: ${(props) => props.color || 'red'};
`
​
export default class App extends Component {
  render() {
    return (
      <div>
        App
        <Title>标题内容一</Title>
        <Title1>标题内容二</Title1>
        <Color>红色文字</Color>
        <Color color="green">绿色文字</Color>
      </div>
    )
  }
}
复制代码

5、scss的使用

scss是成熟、稳定的流行的css预编译处理器

在react使用create-react-app脚手架中,内部已经将scss的样式编译配置完成,但是编译器的依赖需要自行安装。

复制代码
# 安装sass编译器
javascript 复制代码
npm i -D sass

src\assets\styles\App.module.scss

复制代码
// 变量声明定义
javascript 复制代码
$pramiry-color: red;
.item {
  display: flex;
  justify-content: space-between;
  padding: 5px;
  // scss嵌套写法
  > div:first-child {
    width: 30%;
  }
  > div:nth-child(2) {
    width: 60%;
    margin-left: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    > div:first-child {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    > div:nth-child(2) {
      // 变量使用
      color: $pramiry-color;
    }
  }
}
复制代码

src\App.js

javascript 复制代码
import React, { Component } from 'react'
/****
 * scss
 * 选择器嵌套写法  变量的使用
 *
 *
 */
import styled from './assets/styles/App.module.scss'
export default class App extends Component {
  render() {
    return (
      <div className={styled.item}>
        <div>
          <img
            src="http://dingyue.ws.126.net/2021/0201/b63f2e50j00qntwfh0020c000hs00npg.jpg?imageView&thumbnail=140y88&quality=85"
            alt=""
          />
        </div>
        <div>
          <div>被指偷拿半卷卫生纸 63岁女洗碗工服药自杀 酒店回应</div>
          <div>2021-02-02 10:00:51</div>
        </div>
      </div>
    )
  }
}
复制代码

6、less的使用

less支持浏览器和开发者服务器编译两种方式。

默认react脚手架create-react-app默认只支持scss,如果使用less需要解构配置文件,并安装编译器和加载器进行使用

src\assets\styles\App.module.less

javascript 复制代码
// 变量声明定义
@pramiry-color: red;
.item {
  display: flex;
  justify-content: space-between;
  padding: 5px;
  > div:first-child {
    width: 30%;
  }
  > div:nth-child(2) {
    width: 60%;
    margin-left: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    > div:first-child {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    > div:nth-child(2) {
      // 变量使用
      color:@pramiry-color;
    }
  }
}

①安装less的编译器和加载器

javascript 复制代码
npm i -D less less-loader

②解构配置文件

javascript 复制代码
npm run eject

③配置解析less文件

config\webpack.config.js

配置识别文件后缀、文件扩展名

配置loader加载器调用对应的编译器解析编译文件中的语法

javascript 复制代码
//.............................
/***配置less-loader 开始 */
            {
              test: lessRegex,
              exclude: lessModuleRegex,
              use: getStyleLoaders(
                {
                  importLoaders: 3,
                  sourceMap: isEnvProduction
                    ? shouldUseSourceMap
                    : isEnvDevelopment,
                  modules: {
                    mode: 'icss'
                  }
                },
                'less-loader'
              ),
              // Don't consider CSS imports dead code even if the
              // containing package claims to have no side effects.
              // Remove this when webpack adds a warning or an error for this.
              // See https://github.com/webpack/webpack/issues/6571
              sideEffects: true
            },
            // Adds support for CSS Modules, but using SASS
            // using the extension .module.scss or .module.sass
            {
              test: lessModuleRegex,
              use: getStyleLoaders(
                {
                  importLoaders: 3,
                  sourceMap: isEnvProduction
                    ? shouldUseSourceMap
                    : isEnvDevelopment,
                  modules: {
                    mode: 'local',
                    getLocalIdent: getCSSModuleLocalIdent
                  }
                },
                'less-loader'
              )
            },
            /***配置less-loader 结束*/
//.............................

内联样式(Inline Styles)

javascript 复制代码
   import React from 'react';

   function MyComponent() {
     const customColor = '#ff0066';
     return (
       <div style={{
         color: customColor,
         fontSize: '18px',
         backgroundColor: 'lightgray',
         padding: '10px',
         borderRadius: '5px',
       }}>
         This is a styled component using inline styles.
       </div>
     );
   }

   export default MyComponent;

在上述代码中,style 属性接收一个对象,其键是 CSS 属性名(驼峰式或全小写),值是相应的 CSS 属性值。这种方法可以利用 JavaScript 的表达式来实现动态样式计算。

相关推荐
一个天蝎座 白勺 程序猿4 分钟前
Python练习(1)Python基础类型操作语法实战:20道实战题解与案例分析(上)
开发语言·python·学习
lightqjx13 分钟前
【数据结构】顺序表(sequential list)
c语言·开发语言·数据结构·算法
多啦C梦a14 分钟前
【前端必修】闭包、`this`、`箭头函数`、`bind`、节流,一篇文章全懂!
前端·javascript·html
归于尽14 分钟前
为什么别人用闭包那么溜?这 8 个场景照着用就对了
前端·javascript·面试
Hilaku17 分钟前
Vue 2与Vue 3响应式原理的对比与实现
前端·javascript·vue.js
自出洞来无敌手(曾令瑶)22 分钟前
浏览器 实时监听音量 实时语音识别 vue js
前端·javascript·vue.js·语音识别
巨人张23 分钟前
信息素养Python编程题
开发语言·python
Hilaku1 小时前
“虚拟DOM”到底是什么?我们用300行代码来实现一个
前端·javascript·vue.js
阿猿收手吧!1 小时前
【计算机网络】HTTP1.0 HTTP1.1 HTTP2.0 QUIC HTTP3 究极总结
开发语言·计算机网络