react 中样式写法

方式一:行内样式:

优点:

基于内联样式书写的样式肯定不会导致样式冲突,可以动态获取state中的状态来完成动态样式

缺点:

采用小驼峰写法, 有的css书写没有提示易错,在JSX中写大量的style样式,比较混乱,伪类, 伪元素这种样式无法通过内联样式编写。

import React, { Component } from 'react';

class ReactStyle extends Component {
  constructor(props) {
    super(props);
    // 动态改变样式
    this.state = { textColor: 'orange' }
  }
  render() { 
    // 将样式抽取到一个变量中
    const h2Style = { fontSize: '26px', color: 'red' }
    return (
      <div>
        <h2 style={ h2Style }>我是H2标签</h2>
        <p style={{ fontSize: '36px', color: 'blue' }}>我是p标签</p>
        <div style={{ color: this.state.textColor }}>我是div标签</div>
      </div>
    )
  }
}
export default ReactStyle;

方式二:外部样式(在组件中引入外部的样式文件):使用外部样式时要注意类名避免冲突

定义 out.js 组件:

import React, { Component } from 'react';
import './out.css'; // 引入外部样式

class Out extends Component { 
  constructor(props) {
    super(props);
  }
  render() { 
    return (
      <div className='out'>我是使用外部样式渲染后的结果</div>
    )
  }
}

export default Out;

定义外部样式文件 out.css

.out{
  font-size: 30px;
  color: skyblue;
  background: orangered;
}

方式三:css-in-js

在React中有css-in-js,它是一种模式,这个css由js生成而不是在外部文件中定义,是CSS Modules,主要是借助第三方库生成随机类名称的方式来建立一种局部类名的方式

这种css-in-js的第三方模块有很多:可以访问:https://github.com/MicheleBertoli/css-in-js

方式四:styled-components

使用styled-components 的好处是,它可以让组件自己的样式对自己生效,不是全局样式,做到互不干扰;

首先通过npm 或者 cnpm 进行安装styled-components 模块;        

npm install -S styled-components

在某个文件中使用styled-components时,通过import 的方式引入该模块;

import styled from "styled-components"; // 引入styled-components库,实例化styled对象

例子:

组件ButtonA.js

import styled from 'styled-components'; // 引入styled-components组件
// 生命样式 ButtonA组件,通过styled 对象进行创建,注意styled.hlml 元素后面是 反引号;
const ButtonA = styled.button`
  width: 100px;
  height: 30px;
  border:1px solid red;
  color: blue;
`;
// 对外暴露出去
export {
  ButtonA
}

 组件 ButtonB.js 

import styled from 'styled-components'; // 引入styled-components组件
// 生命样式 ButtonA组件,通过styled 对象进行创建,注意styled.hlml 元素后面是 反引号;
const ButtonB = styled.button`
  width: 120px;
  height: 40px;
  border: 1 px solid blue;
  color: red;
`;
// 对外暴露出去
export {
  ButtonB
}

 StyledComponents.js 组件:

import React, { Component } from 'react';
import { ButtonA } from './components/ButtonA';
import { ButtonB } from './components/ButtonB';
// 要避免在render方法中声明样式化组件

class StyledComponents extends Component { 
  render() { 
    return (
      <>
        <ButtonA>按钮A</ButtonA>
        <ButtonB>按钮B</ButtonB>
      </>
    )
  }
}
export default StyledComponents;

在其他页面中可以使用过StyledComponents组件了。以上组件都没有传递参数;

样式组件可以接收props
 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值