00007.样式的模块化

2025-04-14  本文已影响0人  笑着字太黑

1.Angular

通过组件的装饰器styleUrls引入(通常是.css或.scss文件),
Angular默认使用ViewEncapsulation.Emulated来封装组件的样式,这意味着样式会被限制在组件内部,不会影响到外部。但你可以改变这种封装方式,例如使用ViewEncapsulation.None或ViewEncapsulation.ShadowDom,这样可以让样式穿透封装,应用到父组件或其他组件上。例如:

import { Component } from '@angular/core';
 
@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  encapsulation: ViewEncapsulation.None,
  styleUrls: ['./my-component.component.css']  // 引入CSS文件
})
export class MyComponent { }

2.Vue

在Vue单文件组件中,使用<style>标签定义样式
你可以使用<style>标签的scoped属性来确保样式只应用于当前组件,而不会影响到其他组件。
如果希望子组件也可以使用父组件定义的样式,那就不要使用<style>标签的scoped属性

<template>
  <div class="example">Hello World</div>
</template>
 
<script>
export default {
  name: 'ExampleComponent'
}
</script>
 
<style scoped>
.example {
  color: red;
}
</style>

在.vue文件中使用Sass

<style scoped lang="scss">
</style>

React

(React定义的式样好像默认是全局公用的,无法控制,学习中还不太确定)
将CSS文件定义为模块化文件xxx.module.css,然后在导入时可以指定导入的CSS模块名字来控制使用范围。

创建CSS文件:例如,Button.module.css。
/* Button.module.css */
.button {
  background-color: blue;
  color: white;
  padding: 10px;
  border: none;
  border-radius: 5px;
}
在React组件中导入并使用CSS模块:可以给导入的CSS模块指定个名字来使用(这里是styles)
import React from 'react';
import styles from './Button.module.css'; // 导入CSS模块
 
function Button() {
  return <button className={styles.button}>Click me</button>; // 使用模块化的类名
}
 
export default Button;
上一篇 下一篇

猜你喜欢

热点阅读