react-CSS学习

react-CSS学习

1、内联样式(不推荐):

写法:style接收一个采用小驼峰命名属性的JavaScript对象,而不是CSS字符串,并且可以引用state中的状态来设置相关样式

优点:内联样式,样式之间不存在冲突,可以动态获取当前state中的状态

import React, { PureComponent } from 'react';

export default class App extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      color: 'purple',
    };
  }
  render() {
    const pStyle = {
      color: this.state.color,
      textDecoration: 'underline',
    };
    return (
      <div>
        <h2 style={{ fontSize: '50px', color: 'red' }}>我是标题</h2>
        <p style={pStyle}>我是一段文字描述</p>
      </div>
    );
  }
}

2、普通CSS样式:

需要单独引入一个文件,存在样式覆盖的问题

.js
import React, { PureComponent } from 'react';
//需要导入
import './style.css';

export default class Home extends PureComponent {
  render() {
    return (
      <div className='home'>
        <h2 className='title'>我是home的标题</h2>
        <div className='banner'>
          <span>轮播图</span>
        </div>
      </div>
    );
  }
}
.css
.home .title {
  font-size: 30px;
  color: red;
}

.home .banner {
  color: orange;
}

3、css modules

react脚手架内置css modules:.css/.less/.scss等样式文件都修改成了.module.css/.less/.scss,可以直接引用

使用modules就要将css当成模块化开发,需要添加标识符指向该css文件

拿到相关模块,再使用模块中的相关属性

解决了样式冲突样式层叠的问题

问题:

1、但是遇到连接符“-”时,需要使用小驼峰

2、所有的className都需要使用style.className的形式来编写(可以使用对象解构)

3、不方便动态添加样式,需要采用内联样式

index.js
import React, { PureComponent } from 'react';

import style from './style.module.css';

export default class Profile extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      color: 'purple',
    };
  }
  render() {
    return (
      <div className='profile'>
        <h2 className={style.title} style={{ color: this.state.color }}>
          我是Profile的标题
        </h2>
        <ul className={style.settings}>
          <li className={style.settingItem}>设置列表1</li>
          <li>设置列表2</li>
          <li>设置列表3</li>
        </ul>
      </div>
    );
  }
}
style.module.css
.title {
  color: yellow;
}

4、CSS in JS

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值