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 的表达式来实现动态样式计算。

相关推荐
刘发财2 小时前
弃用html2pdf.js,这个html转pdf方案能力是它的几十倍
前端·javascript·github
ssshooter8 小时前
看完就懂 useSyncExternalStore
前端·javascript·react.js
Live0000010 小时前
在鸿蒙中使用 Repeat 渲染嵌套列表,修改内层列表的一个元素,页面不会更新
前端·javascript·react native
柳杉10 小时前
使用Ai从零开发智慧水利态势感知大屏(开源)
前端·javascript·数据可视化
球球pick小樱花10 小时前
游戏官网前端工具库:海内外案例解析
前端·javascript·css
喝水的长颈鹿10 小时前
【大白话前端 02】网页从解析到绘制的全流程
前端·javascript
用户145369814587810 小时前
VersionCheck.js - 让前端版本更新变得简单优雅
前端·javascript
codingWhat10 小时前
整理「祖传」代码,就是在开发脚手架?
前端·javascript·node.js
码路飞11 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
Lee川11 小时前
优雅进化的JavaScript:从ES6+新特性看现代前端开发范式
javascript·面试