在 react 当中有提供了不同的 css 方法,除了常见的 css in css 外, 另外现在前端主流使用的 style system, css in js (styled component, emotion) 和 utility (tailwind) 等,以下会先从最传统的 css in css 介绍起。 为了方便,以下范例都以 create-react-app 为主,除了 sass, 不另外使用 webpack
在 React 当中如果要使用全域的 CSS ,可以在 index.js 或是 App.js 引入
只要用 import 的方式就可引入,注意的是这边引入的 css 是全域,只要其他的 component 有重复
class name,皆有可能此 css 的样式
//App.js
import 'App.css'
function App (){
return (<div className="continer">
<Button/>
</div>)
}
上面 div 的 className 编译纯 html 後会变成
<div class="container"></div>
function Button (){
<div className="container">
// 因为 App.js 有引入 App.css,包含 container class,
这边的 container 也会吃到 container 样式
</div>
}
上叙因为 stylesheet 的方式会造成 class 样式对於全域的污染, 所以我们可以把我们的 css 档命成, [name].module.css
, ex: 档名为 Button.module.css
的 css 档, 在此范围内的 css档,在每一个 className 都会产生 hash, 所以每一个 className 都不会污染其他 className, create react app 的 hash 规则为 [filename]\_[classname]\_\_[hash]
以下为范例
// Button.module.css
.button{
width:100px;
height:40px;
border-radious:50%;
text-align:center;
line-height:40px;
}
// Button.js
import style form './Button.module.css'
// style 可以为任意命名,这边取 style 为常用的名称方便辨识
function Button (){
return <button className={style.button}>Open</button>
上面 button 的 className 编译纯 html 後会变成
<div class="Button_container_as345"></div>
}
假设在 CSS module 当中想使用一个 预设 的 button 样式, 另外含有 outline 样式的 button ,我们就可以使用 :global
的语法来使 css 中的 class 具有 global 的效果
// Button.module.css
:global(.button){
width:100px;
height:40px;
border-radious:50%;
text-align:center;
line-height:40px;
}
.buttonOutline{
border:1px solid #FFFFFF;
background-color: #000000;
color: #FFFFFF;
}
// Button.js
import style form './Button.module.css'
function Button (){
return <button className={`button ${style.buttonOutline}`}>Open</button>
上面 button 的 className 编译纯 html 後会变成
<div class="button Button_container_as345"></div>
}
<<: Re: 新手让网页 act 起来: Day05 - 建立元件
>>: CSS就可以!animation 与他的好夥伴 @keyframes
今日文章目录 需求说明 事前准备 遇到问题 参考资料 需求说明 下拉选单:选择番茄钟时间(分钟) ...
来到了最後一天,我们也剩下最後一片云要一起来探索。今天就来谈谈云端的资安,以此来总结我们这一趟经历两...
flutter_native_splash App 启动时的launch画面 首先在pubspec....
特性与用途 不会影响到原始阵列的资料 筛选符合条件的第一笔资料,并且回传至新的阵列 直接进入写法及范...
题号:74 标题:Search a 2D Matrix 难度:Medium Write an eff...