React中组件样式隔~index.module.css(详细版)

若不进行样式隔离,子组件Welcome的样式会覆盖Hello的样式

1.在components下创建两个文件Hello和Welcone分别在两个文件夹内创建index.js和index.module.css文件。

2.在App.js中注册Hello和Welcone组件。

//App.js
import './App.css';  
import Hello from './components/Hello'  //引入Hello组件
import Welcome from './components/Welcome' //引入Welcome组件
function App() {
  return (
    <div className="App">
      <Hello/>    //注册Hello组件  这里hello是先注册的
      <Welcome/>     //注册Welcome组件    welcome是后注册的 记住这是要考的哦
    </div>
  );
}

export default App;

 3.在Hello/index.js和Welcome/index.js文件中写基本语法。

//Hello/index.js文件
import React, {Component} from "react";
import "./index.css"
export default class Hello extends Component {
    render() {
        return <h2 className="title"> Hello React</h2>
    }
}
//Welcome/index.js
import React, {Component} from "react";
import "./index.css"
export default class Hello extends Component {
    render() {
        return <h2 className='title'> Welcome</h2>
    }
}

  4.在Hello/index.css和Welcome/index.css文件中写样式。

//Hello/index.css
.title{
    background-color: pink;
}
//Welcome/index.css
.title{
    background-color: red;
}

 5.页面显示结果

正常我们运行想像出来的结果为上面的背景颜色是粉色,下面的背景颜色是红色。结果为什么显示出来的背景颜色都是红色呢?

因为react组件在页面渲染的前,会将组件的样式“集合”到一起,因为引用组件时,<Welcome/>组件在<Home/>下面,因此<Welcome/>组件的红色会覆盖<Home/>组件的粉色。

//App.js
import './App.css';  
import Hello from './components/Hello'  //引入Hello组件
import Welcome from './components/Welcome' //引入Welcome组件
function App() {
  return (
    <div className="App">
      <Hello/>    //注册Hello组件
      <Welcome/>     //注册Welcome组件  组件<Welcome/>的样式覆盖了<Hello/> 的样式
    </div>
  );
}

export default App;

那若现解决这种样式覆盖,要怎么办呢?

我们可以对想进行组件隔离的样式从新设置一个文件名,改变引入方法。

接下来让我们一起见证吧

现在我们给<Hello/>组件设置样式隔离

一共分两步

 1.更改index.css文件名为index.module.css

 2.改变引入方法在index.js文件中引入方法,和下面使用的时候的调用

   毕竟人家都改名字了,要是还引入index.css可是找不到俺哒。

//index.js文件
import React, {Component} from "react";
//只可以这样引入,不要想可不可以import "./index.module.css" 这样引入下面就不用改了?
//漏··· 大漏特漏··· 不可以 问就是乌龟的屁股“规定” 
import hello from "./index.module.css"  //改变引入方法  
export default class Hello extends Component {
    render() {
        return <h2 className={hello.title}> Hello React</h2>  //这个也要变
    }
}
//index.module.css文件
.title{
    background-color: red;
}
//别看俺,俺就变个文件名,内在没变的啊!!!  
//俺还是那个小红

来看一下运行结果叭~~~上面是粉色,下面是红色,问题解决

总结

react中,组件使用相同样式属性,在父组件中会有样式覆盖问题,下面的组件会覆盖上面组件的样式,解决办法,在子组件中对想进行样式隔离的组件,将其.css文件改名为.module.css文件,在.js文件中改变引入方法的调用,即可实现组件隔离。

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端-rabbit

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值